babylon.no-module.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6093. };
  6094. /**
  6095. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8129. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Interpolates between a and b via alpha
  8579. * @param a The lower value (returned when alpha = 0)
  8580. * @param b The upper value (returned when alpha = 1)
  8581. * @param alpha The interpolation-factor
  8582. * @return The mixed value
  8583. */
  8584. Tools.Mix = function (a, b, alpha) {
  8585. return a * (1 - alpha) + b * alpha;
  8586. };
  8587. Tools.Instantiate = function (className) {
  8588. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8589. return Tools.RegisteredExternalClasses[className];
  8590. }
  8591. var arr = className.split(".");
  8592. var fn = (window || this);
  8593. for (var i = 0, len = arr.length; i < len; i++) {
  8594. fn = fn[arr[i]];
  8595. }
  8596. if (typeof fn !== "function") {
  8597. return null;
  8598. }
  8599. return fn;
  8600. };
  8601. /**
  8602. * Provides a slice function that will work even on IE
  8603. * @param data defines the array to slice
  8604. * @param start defines the start of the data (optional)
  8605. * @param end defines the end of the data (optional)
  8606. * @returns the new sliced array
  8607. */
  8608. Tools.Slice = function (data, start, end) {
  8609. if (data.slice) {
  8610. return data.slice(start, end);
  8611. }
  8612. return Array.prototype.slice.call(data, start, end);
  8613. };
  8614. Tools.SetImmediate = function (action) {
  8615. if (window.setImmediate) {
  8616. window.setImmediate(action);
  8617. }
  8618. else {
  8619. setTimeout(action, 1);
  8620. }
  8621. };
  8622. Tools.IsExponentOfTwo = function (value) {
  8623. var count = 1;
  8624. do {
  8625. count *= 2;
  8626. } while (count < value);
  8627. return count === value;
  8628. };
  8629. /**
  8630. * Returns the nearest 32-bit single precision float representation of a Number
  8631. * @param value A Number. If the parameter is of a different type, it will get converted
  8632. * to a number or to NaN if it cannot be converted
  8633. * @returns number
  8634. */
  8635. Tools.FloatRound = function (value) {
  8636. if (Math.fround) {
  8637. return Math.fround(value);
  8638. }
  8639. return (Tools._tmpFloatArray[0] = value);
  8640. };
  8641. /**
  8642. * Find the next highest power of two.
  8643. * @param x Number to start search from.
  8644. * @return Next highest power of two.
  8645. */
  8646. Tools.CeilingPOT = function (x) {
  8647. x--;
  8648. x |= x >> 1;
  8649. x |= x >> 2;
  8650. x |= x >> 4;
  8651. x |= x >> 8;
  8652. x |= x >> 16;
  8653. x++;
  8654. return x;
  8655. };
  8656. /**
  8657. * Find the next lowest power of two.
  8658. * @param x Number to start search from.
  8659. * @return Next lowest power of two.
  8660. */
  8661. Tools.FloorPOT = function (x) {
  8662. x = x | (x >> 1);
  8663. x = x | (x >> 2);
  8664. x = x | (x >> 4);
  8665. x = x | (x >> 8);
  8666. x = x | (x >> 16);
  8667. return x - (x >> 1);
  8668. };
  8669. /**
  8670. * Find the nearest power of two.
  8671. * @param x Number to start search from.
  8672. * @return Next nearest power of two.
  8673. */
  8674. Tools.NearestPOT = function (x) {
  8675. var c = Tools.CeilingPOT(x);
  8676. var f = Tools.FloorPOT(x);
  8677. return (c - x) > (x - f) ? f : c;
  8678. };
  8679. Tools.GetExponentOfTwo = function (value, max, mode) {
  8680. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8681. var pot;
  8682. switch (mode) {
  8683. case BABYLON.Engine.SCALEMODE_FLOOR:
  8684. pot = Tools.FloorPOT(value);
  8685. break;
  8686. case BABYLON.Engine.SCALEMODE_NEAREST:
  8687. pot = Tools.NearestPOT(value);
  8688. break;
  8689. case BABYLON.Engine.SCALEMODE_CEILING:
  8690. default:
  8691. pot = Tools.CeilingPOT(value);
  8692. break;
  8693. }
  8694. return Math.min(pot, max);
  8695. };
  8696. Tools.GetFilename = function (path) {
  8697. var index = path.lastIndexOf("/");
  8698. if (index < 0)
  8699. return path;
  8700. return path.substring(index + 1);
  8701. };
  8702. /**
  8703. * Extracts the "folder" part of a path (everything before the filename).
  8704. * @param uri The URI to extract the info from
  8705. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8706. * @returns The "folder" part of the path
  8707. */
  8708. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8709. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8710. var index = uri.lastIndexOf("/");
  8711. if (index < 0) {
  8712. if (returnUnchangedIfNoSlash) {
  8713. return uri;
  8714. }
  8715. return "";
  8716. }
  8717. return uri.substring(0, index + 1);
  8718. };
  8719. Tools.GetDOMTextContent = function (element) {
  8720. var result = "";
  8721. var child = element.firstChild;
  8722. while (child) {
  8723. if (child.nodeType === 3) {
  8724. result += child.textContent;
  8725. }
  8726. child = child.nextSibling;
  8727. }
  8728. return result;
  8729. };
  8730. Tools.ToDegrees = function (angle) {
  8731. return angle * 180 / Math.PI;
  8732. };
  8733. Tools.ToRadians = function (angle) {
  8734. return angle * Math.PI / 180;
  8735. };
  8736. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8737. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8738. var output = "";
  8739. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8740. var i = 0;
  8741. var bytes = new Uint8Array(buffer);
  8742. while (i < bytes.length) {
  8743. chr1 = bytes[i++];
  8744. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8745. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8746. enc1 = chr1 >> 2;
  8747. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8748. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8749. enc4 = chr3 & 63;
  8750. if (isNaN(chr2)) {
  8751. enc3 = enc4 = 64;
  8752. }
  8753. else if (isNaN(chr3)) {
  8754. enc4 = 64;
  8755. }
  8756. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8757. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8758. }
  8759. return "data:image/png;base64," + output;
  8760. };
  8761. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8762. if (bias === void 0) { bias = null; }
  8763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8765. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8766. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8767. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8768. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8769. }
  8770. if (bias) {
  8771. minimum.x -= minimum.x * bias.x + bias.y;
  8772. minimum.y -= minimum.y * bias.x + bias.y;
  8773. minimum.z -= minimum.z * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. maximum.z += maximum.z * bias.x + bias.y;
  8777. }
  8778. return {
  8779. minimum: minimum,
  8780. maximum: maximum
  8781. };
  8782. };
  8783. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8784. if (bias === void 0) { bias = null; }
  8785. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8786. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8787. if (!stride) {
  8788. stride = 3;
  8789. }
  8790. for (var index = start; index < start + count; index++) {
  8791. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8792. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8793. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8794. }
  8795. if (bias) {
  8796. minimum.x -= minimum.x * bias.x + bias.y;
  8797. minimum.y -= minimum.y * bias.x + bias.y;
  8798. minimum.z -= minimum.z * bias.x + bias.y;
  8799. maximum.x += maximum.x * bias.x + bias.y;
  8800. maximum.y += maximum.y * bias.x + bias.y;
  8801. maximum.z += maximum.z * bias.x + bias.y;
  8802. }
  8803. return {
  8804. minimum: minimum,
  8805. maximum: maximum
  8806. };
  8807. };
  8808. Tools.Vector2ArrayFeeder = function (array) {
  8809. return function (index) {
  8810. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8811. var length = isFloatArray ? array.length / 2 : array.length;
  8812. if (index >= length) {
  8813. return null;
  8814. }
  8815. if (isFloatArray) {
  8816. var fa = array;
  8817. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8818. }
  8819. var a = array;
  8820. return a[index];
  8821. };
  8822. };
  8823. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8824. if (bias === void 0) { bias = null; }
  8825. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8826. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8827. var i = 0;
  8828. var cur = feeder(i++);
  8829. while (cur) {
  8830. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8831. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8832. cur = feeder(i++);
  8833. }
  8834. if (bias) {
  8835. minimum.x -= minimum.x * bias.x + bias.y;
  8836. minimum.y -= minimum.y * bias.x + bias.y;
  8837. maximum.x += maximum.x * bias.x + bias.y;
  8838. maximum.y += maximum.y * bias.x + bias.y;
  8839. }
  8840. return {
  8841. minimum: minimum,
  8842. maximum: maximum
  8843. };
  8844. };
  8845. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8846. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8847. return null;
  8848. return Array.isArray(obj) ? obj : [obj];
  8849. };
  8850. // Misc.
  8851. Tools.GetPointerPrefix = function () {
  8852. var eventPrefix = "pointer";
  8853. // Check if pointer events are supported
  8854. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8855. eventPrefix = "mouse";
  8856. }
  8857. return eventPrefix;
  8858. };
  8859. /**
  8860. * @param func - the function to be called
  8861. * @param requester - the object that will request the next frame. Falls back to window.
  8862. */
  8863. Tools.QueueNewFrame = function (func, requester) {
  8864. if (!Tools.IsWindowObjectExist()) {
  8865. return setTimeout(func, 16);
  8866. }
  8867. if (!requester) {
  8868. requester = window;
  8869. }
  8870. if (requester.requestAnimationFrame) {
  8871. return requester.requestAnimationFrame(func);
  8872. }
  8873. else if (requester.msRequestAnimationFrame) {
  8874. return requester.msRequestAnimationFrame(func);
  8875. }
  8876. else if (requester.webkitRequestAnimationFrame) {
  8877. return requester.webkitRequestAnimationFrame(func);
  8878. }
  8879. else if (requester.mozRequestAnimationFrame) {
  8880. return requester.mozRequestAnimationFrame(func);
  8881. }
  8882. else if (requester.oRequestAnimationFrame) {
  8883. return requester.oRequestAnimationFrame(func);
  8884. }
  8885. else {
  8886. return window.setTimeout(func, 16);
  8887. }
  8888. };
  8889. Tools.RequestFullscreen = function (element) {
  8890. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8891. if (!requestFunction)
  8892. return;
  8893. requestFunction.call(element);
  8894. };
  8895. Tools.ExitFullscreen = function () {
  8896. if (document.exitFullscreen) {
  8897. document.exitFullscreen();
  8898. }
  8899. else if (document.mozCancelFullScreen) {
  8900. document.mozCancelFullScreen();
  8901. }
  8902. else if (document.webkitCancelFullScreen) {
  8903. document.webkitCancelFullScreen();
  8904. }
  8905. else if (document.msCancelFullScreen) {
  8906. document.msCancelFullScreen();
  8907. }
  8908. };
  8909. Tools.SetCorsBehavior = function (url, element) {
  8910. if (url && url.indexOf("data:") === 0) {
  8911. return;
  8912. }
  8913. if (Tools.CorsBehavior) {
  8914. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8915. element.crossOrigin = Tools.CorsBehavior;
  8916. }
  8917. else {
  8918. var result = Tools.CorsBehavior(url);
  8919. if (result) {
  8920. element.crossOrigin = result;
  8921. }
  8922. }
  8923. }
  8924. };
  8925. // External files
  8926. Tools.CleanUrl = function (url) {
  8927. url = url.replace(/#/mg, "%23");
  8928. return url;
  8929. };
  8930. /**
  8931. * Loads an image as an HTMLImageElement.
  8932. * @param input url string, ArrayBuffer, or Blob to load
  8933. * @param onLoad callback called when the image successfully loads
  8934. * @param onError callback called when the image fails to load
  8935. * @param database database for caching
  8936. * @returns the HTMLImageElement of the loaded image
  8937. */
  8938. Tools.LoadImage = function (input, onLoad, onError, database) {
  8939. var url;
  8940. var usingObjectURL = false;
  8941. if (input instanceof ArrayBuffer) {
  8942. url = URL.createObjectURL(new Blob([input]));
  8943. usingObjectURL = true;
  8944. }
  8945. else if (input instanceof Blob) {
  8946. url = URL.createObjectURL(input);
  8947. usingObjectURL = true;
  8948. }
  8949. else {
  8950. url = Tools.CleanUrl(input);
  8951. url = Tools.PreprocessUrl(input);
  8952. }
  8953. var img = new Image();
  8954. Tools.SetCorsBehavior(url, img);
  8955. var loadHandler = function () {
  8956. if (usingObjectURL && img.src) {
  8957. URL.revokeObjectURL(img.src);
  8958. }
  8959. img.removeEventListener("load", loadHandler);
  8960. img.removeEventListener("error", errorHandler);
  8961. onLoad(img);
  8962. };
  8963. var errorHandler = function (err) {
  8964. if (usingObjectURL && img.src) {
  8965. URL.revokeObjectURL(img.src);
  8966. }
  8967. img.removeEventListener("load", loadHandler);
  8968. img.removeEventListener("error", errorHandler);
  8969. Tools.Error("Error while trying to load image: " + input);
  8970. if (onError) {
  8971. onError("Error while trying to load image: " + input, err);
  8972. }
  8973. };
  8974. img.addEventListener("load", loadHandler);
  8975. img.addEventListener("error", errorHandler);
  8976. var noIndexedDB = function () {
  8977. img.src = url;
  8978. };
  8979. var loadFromIndexedDB = function () {
  8980. if (database) {
  8981. database.loadImageFromDB(url, img);
  8982. }
  8983. };
  8984. //ANY database to do!
  8985. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8986. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8987. }
  8988. else {
  8989. if (url.indexOf("file:") !== -1) {
  8990. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8991. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8992. try {
  8993. var blobURL;
  8994. try {
  8995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8996. }
  8997. catch (ex) {
  8998. // Chrome doesn't support oneTimeOnly parameter
  8999. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9000. }
  9001. img.src = blobURL;
  9002. usingObjectURL = true;
  9003. }
  9004. catch (e) {
  9005. img.src = "";
  9006. }
  9007. return img;
  9008. }
  9009. }
  9010. noIndexedDB();
  9011. }
  9012. return img;
  9013. };
  9014. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9015. url = Tools.CleanUrl(url);
  9016. url = Tools.PreprocessUrl(url);
  9017. // If file and file input are set
  9018. if (url.indexOf("file:") !== -1) {
  9019. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9020. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9021. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9022. }
  9023. }
  9024. var loadUrl = Tools.BaseUrl + url;
  9025. var aborted = false;
  9026. var fileRequest = {
  9027. onCompleteObservable: new BABYLON.Observable(),
  9028. abort: function () { return aborted = true; },
  9029. };
  9030. var requestFile = function () {
  9031. var request = new XMLHttpRequest();
  9032. var retryHandle = null;
  9033. fileRequest.abort = function () {
  9034. aborted = true;
  9035. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9036. request.abort();
  9037. }
  9038. if (retryHandle !== null) {
  9039. clearTimeout(retryHandle);
  9040. retryHandle = null;
  9041. }
  9042. };
  9043. var retryLoop = function (retryIndex) {
  9044. request.open('GET', loadUrl, true);
  9045. if (useArrayBuffer) {
  9046. request.responseType = "arraybuffer";
  9047. }
  9048. if (onProgress) {
  9049. request.addEventListener("progress", onProgress);
  9050. }
  9051. var onLoadEnd = function () {
  9052. request.removeEventListener("loadend", onLoadEnd);
  9053. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9054. fileRequest.onCompleteObservable.clear();
  9055. };
  9056. request.addEventListener("loadend", onLoadEnd);
  9057. var onReadyStateChange = function () {
  9058. if (aborted) {
  9059. return;
  9060. }
  9061. // In case of undefined state in some browsers.
  9062. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9063. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9064. request.removeEventListener("readystatechange", onReadyStateChange);
  9065. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9066. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9067. return;
  9068. }
  9069. var retryStrategy = Tools.DefaultRetryStrategy;
  9070. if (retryStrategy) {
  9071. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9072. if (waitTime !== -1) {
  9073. // Prevent the request from completing for retry.
  9074. request.removeEventListener("loadend", onLoadEnd);
  9075. request = new XMLHttpRequest();
  9076. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9077. return;
  9078. }
  9079. }
  9080. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9081. if (onError) {
  9082. onError(request, e);
  9083. }
  9084. else {
  9085. throw e;
  9086. }
  9087. }
  9088. };
  9089. request.addEventListener("readystatechange", onReadyStateChange);
  9090. request.send();
  9091. };
  9092. retryLoop(0);
  9093. };
  9094. // Caching all files
  9095. if (database && database.enableSceneOffline) {
  9096. var noIndexedDB_1 = function () {
  9097. if (!aborted) {
  9098. requestFile();
  9099. }
  9100. };
  9101. var loadFromIndexedDB = function () {
  9102. // TODO: database needs to support aborting and should return a IFileRequest
  9103. if (aborted) {
  9104. return;
  9105. }
  9106. if (database) {
  9107. database.loadFileFromDB(url, function (data) {
  9108. if (!aborted) {
  9109. onSuccess(data);
  9110. }
  9111. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9112. }, onProgress ? function (event) {
  9113. if (!aborted) {
  9114. onProgress(event);
  9115. }
  9116. } : undefined, noIndexedDB_1, useArrayBuffer);
  9117. }
  9118. };
  9119. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9120. }
  9121. else {
  9122. requestFile();
  9123. }
  9124. return fileRequest;
  9125. };
  9126. /**
  9127. * Load a script (identified by an url). When the url returns, the
  9128. * content of this file is added into a new script element, attached to the DOM (body element)
  9129. */
  9130. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9131. var head = document.getElementsByTagName('head')[0];
  9132. var script = document.createElement('script');
  9133. script.type = 'text/javascript';
  9134. script.src = scriptUrl;
  9135. script.onload = function () {
  9136. if (onSuccess) {
  9137. onSuccess();
  9138. }
  9139. };
  9140. script.onerror = function (e) {
  9141. if (onError) {
  9142. onError("Unable to load script '" + scriptUrl + "'", e);
  9143. }
  9144. };
  9145. head.appendChild(script);
  9146. };
  9147. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9148. var reader = new FileReader();
  9149. var request = {
  9150. onCompleteObservable: new BABYLON.Observable(),
  9151. abort: function () { return reader.abort(); },
  9152. };
  9153. reader.onloadend = function (e) {
  9154. request.onCompleteObservable.notifyObservers(request);
  9155. };
  9156. reader.onload = function (e) {
  9157. //target doesn't have result from ts 1.3
  9158. callback(e.target['result']);
  9159. };
  9160. reader.onprogress = progressCallback;
  9161. reader.readAsDataURL(fileToLoad);
  9162. return request;
  9163. };
  9164. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9165. var reader = new FileReader();
  9166. var request = {
  9167. onCompleteObservable: new BABYLON.Observable(),
  9168. abort: function () { return reader.abort(); },
  9169. };
  9170. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9171. reader.onerror = function (e) {
  9172. Tools.Log("Error while reading file: " + fileToLoad.name);
  9173. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9174. };
  9175. reader.onload = function (e) {
  9176. //target doesn't have result from ts 1.3
  9177. callback(e.target['result']);
  9178. };
  9179. if (progressCallBack) {
  9180. reader.onprogress = progressCallBack;
  9181. }
  9182. if (!useArrayBuffer) {
  9183. // Asynchronous read
  9184. reader.readAsText(fileToLoad);
  9185. }
  9186. else {
  9187. reader.readAsArrayBuffer(fileToLoad);
  9188. }
  9189. return request;
  9190. };
  9191. //returns a downloadable url to a file content.
  9192. Tools.FileAsURL = function (content) {
  9193. var fileBlob = new Blob([content]);
  9194. var url = window.URL || window.webkitURL;
  9195. var link = url.createObjectURL(fileBlob);
  9196. return link;
  9197. };
  9198. // Misc.
  9199. Tools.Format = function (value, decimals) {
  9200. if (decimals === void 0) { decimals = 2; }
  9201. return value.toFixed(decimals);
  9202. };
  9203. Tools.CheckExtends = function (v, min, max) {
  9204. if (v.x < min.x)
  9205. min.x = v.x;
  9206. if (v.y < min.y)
  9207. min.y = v.y;
  9208. if (v.z < min.z)
  9209. min.z = v.z;
  9210. if (v.x > max.x)
  9211. max.x = v.x;
  9212. if (v.y > max.y)
  9213. max.y = v.y;
  9214. if (v.z > max.z)
  9215. max.z = v.z;
  9216. };
  9217. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9218. for (var prop in source) {
  9219. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9220. continue;
  9221. }
  9222. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9223. continue;
  9224. }
  9225. var sourceValue = source[prop];
  9226. var typeOfSourceValue = typeof sourceValue;
  9227. if (typeOfSourceValue === "function") {
  9228. continue;
  9229. }
  9230. try {
  9231. if (typeOfSourceValue === "object") {
  9232. if (sourceValue instanceof Array) {
  9233. destination[prop] = [];
  9234. if (sourceValue.length > 0) {
  9235. if (typeof sourceValue[0] == "object") {
  9236. for (var index = 0; index < sourceValue.length; index++) {
  9237. var clonedValue = cloneValue(sourceValue[index], destination);
  9238. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9239. destination[prop].push(clonedValue);
  9240. }
  9241. }
  9242. }
  9243. else {
  9244. destination[prop] = sourceValue.slice(0);
  9245. }
  9246. }
  9247. }
  9248. else {
  9249. destination[prop] = cloneValue(sourceValue, destination);
  9250. }
  9251. }
  9252. else {
  9253. destination[prop] = sourceValue;
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Just ignore error (it could be because of a read-only property)
  9258. }
  9259. }
  9260. };
  9261. Tools.IsEmpty = function (obj) {
  9262. for (var i in obj) {
  9263. if (obj.hasOwnProperty(i)) {
  9264. return false;
  9265. }
  9266. }
  9267. return true;
  9268. };
  9269. Tools.RegisterTopRootEvents = function (events) {
  9270. for (var index = 0; index < events.length; index++) {
  9271. var event = events[index];
  9272. window.addEventListener(event.name, event.handler, false);
  9273. try {
  9274. if (window.parent) {
  9275. window.parent.addEventListener(event.name, event.handler, false);
  9276. }
  9277. }
  9278. catch (e) {
  9279. // Silently fails...
  9280. }
  9281. }
  9282. };
  9283. Tools.UnregisterTopRootEvents = function (events) {
  9284. for (var index = 0; index < events.length; index++) {
  9285. var event = events[index];
  9286. window.removeEventListener(event.name, event.handler);
  9287. try {
  9288. if (window.parent) {
  9289. window.parent.removeEventListener(event.name, event.handler);
  9290. }
  9291. }
  9292. catch (e) {
  9293. // Silently fails...
  9294. }
  9295. }
  9296. };
  9297. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9298. if (mimeType === void 0) { mimeType = "image/png"; }
  9299. // Read the contents of the framebuffer
  9300. var numberOfChannelsByLine = width * 4;
  9301. var halfHeight = height / 2;
  9302. //Reading datas from WebGL
  9303. var data = engine.readPixels(0, 0, width, height);
  9304. //To flip image on Y axis.
  9305. for (var i = 0; i < halfHeight; i++) {
  9306. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9307. var currentCell = j + i * numberOfChannelsByLine;
  9308. var targetLine = height - i - 1;
  9309. var targetCell = j + targetLine * numberOfChannelsByLine;
  9310. var temp = data[currentCell];
  9311. data[currentCell] = data[targetCell];
  9312. data[targetCell] = temp;
  9313. }
  9314. }
  9315. // Create a 2D canvas to store the result
  9316. if (!screenshotCanvas) {
  9317. screenshotCanvas = document.createElement('canvas');
  9318. }
  9319. screenshotCanvas.width = width;
  9320. screenshotCanvas.height = height;
  9321. var context = screenshotCanvas.getContext('2d');
  9322. if (context) {
  9323. // Copy the pixels to a 2D canvas
  9324. var imageData = context.createImageData(width, height);
  9325. var castData = (imageData.data);
  9326. castData.set(data);
  9327. context.putImageData(imageData, 0, 0);
  9328. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9329. }
  9330. };
  9331. /**
  9332. * Converts the canvas data to blob.
  9333. * This acts as a polyfill for browsers not supporting the to blob function.
  9334. * @param canvas Defines the canvas to extract the data from
  9335. * @param successCallback Defines the callback triggered once the data are available
  9336. * @param mimeType Defines the mime type of the result
  9337. */
  9338. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9339. if (mimeType === void 0) { mimeType = "image/png"; }
  9340. // We need HTMLCanvasElement.toBlob for HD screenshots
  9341. if (!canvas.toBlob) {
  9342. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9343. canvas.toBlob = function (callback, type, quality) {
  9344. var _this = this;
  9345. setTimeout(function () {
  9346. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9347. for (var i = 0; i < len; i++) {
  9348. arr[i] = binStr.charCodeAt(i);
  9349. }
  9350. callback(new Blob([arr]));
  9351. });
  9352. };
  9353. }
  9354. canvas.toBlob(function (blob) {
  9355. successCallback(blob);
  9356. }, mimeType);
  9357. };
  9358. /**
  9359. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9360. * @param successCallback Defines the callback triggered once the data are available
  9361. * @param mimeType Defines the mime type of the result
  9362. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9363. */
  9364. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9365. if (mimeType === void 0) { mimeType = "image/png"; }
  9366. if (successCallback) {
  9367. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9368. successCallback(base64Image);
  9369. }
  9370. else {
  9371. this.ToBlob(screenshotCanvas, function (blob) {
  9372. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9373. if (("download" in document.createElement("a"))) {
  9374. if (!fileName) {
  9375. var date = new Date();
  9376. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9377. fileName = "screenshot_" + stringDate + ".png";
  9378. }
  9379. Tools.Download(blob, fileName);
  9380. }
  9381. else {
  9382. var url = URL.createObjectURL(blob);
  9383. var newWindow = window.open("");
  9384. if (!newWindow)
  9385. return;
  9386. var img = newWindow.document.createElement("img");
  9387. img.onload = function () {
  9388. // no longer need to read the blob so it's revoked
  9389. URL.revokeObjectURL(url);
  9390. };
  9391. img.src = url;
  9392. newWindow.document.body.appendChild(img);
  9393. }
  9394. }, mimeType);
  9395. }
  9396. };
  9397. /**
  9398. * Downloads a blob in the browser
  9399. * @param blob defines the blob to download
  9400. * @param fileName defines the name of the downloaded file
  9401. */
  9402. Tools.Download = function (blob, fileName) {
  9403. var url = window.URL.createObjectURL(blob);
  9404. var a = document.createElement("a");
  9405. document.body.appendChild(a);
  9406. a.style.display = "none";
  9407. a.href = url;
  9408. a.download = fileName;
  9409. a.addEventListener("click", function () {
  9410. if (a.parentElement) {
  9411. a.parentElement.removeChild(a);
  9412. }
  9413. });
  9414. a.click();
  9415. window.URL.revokeObjectURL(url);
  9416. };
  9417. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9418. if (mimeType === void 0) { mimeType = "image/png"; }
  9419. var width;
  9420. var height;
  9421. // If a precision value is specified
  9422. if (size.precision) {
  9423. width = Math.round(engine.getRenderWidth() * size.precision);
  9424. height = Math.round(width / engine.getAspectRatio(camera));
  9425. }
  9426. else if (size.width && size.height) {
  9427. width = size.width;
  9428. height = size.height;
  9429. }
  9430. //If passing only width, computing height to keep display canvas ratio.
  9431. else if (size.width && !size.height) {
  9432. width = size.width;
  9433. height = Math.round(width / engine.getAspectRatio(camera));
  9434. }
  9435. //If passing only height, computing width to keep display canvas ratio.
  9436. else if (size.height && !size.width) {
  9437. height = size.height;
  9438. width = Math.round(height * engine.getAspectRatio(camera));
  9439. }
  9440. //Assuming here that "size" parameter is a number
  9441. else if (!isNaN(size)) {
  9442. height = size;
  9443. width = size;
  9444. }
  9445. else {
  9446. Tools.Error("Invalid 'size' parameter !");
  9447. return;
  9448. }
  9449. if (!screenshotCanvas) {
  9450. screenshotCanvas = document.createElement('canvas');
  9451. }
  9452. screenshotCanvas.width = width;
  9453. screenshotCanvas.height = height;
  9454. var renderContext = screenshotCanvas.getContext("2d");
  9455. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9456. var newWidth = width;
  9457. var newHeight = newWidth / ratio;
  9458. if (newHeight > height) {
  9459. newHeight = height;
  9460. newWidth = newHeight * ratio;
  9461. }
  9462. var offsetX = Math.max(0, width - newWidth) / 2;
  9463. var offsetY = Math.max(0, height - newHeight) / 2;
  9464. var renderingCanvas = engine.getRenderingCanvas();
  9465. if (renderContext && renderingCanvas) {
  9466. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9467. }
  9468. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9469. };
  9470. /**
  9471. * Generates an image screenshot from the specified camera.
  9472. *
  9473. * @param engine The engine to use for rendering
  9474. * @param camera The camera to use for rendering
  9475. * @param size This parameter can be set to a single number or to an object with the
  9476. * following (optional) properties: precision, width, height. If a single number is passed,
  9477. * it will be used for both width and height. If an object is passed, the screenshot size
  9478. * will be derived from the parameters. The precision property is a multiplier allowing
  9479. * rendering at a higher or lower resolution.
  9480. * @param successCallback The callback receives a single parameter which contains the
  9481. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9482. * src parameter of an <img> to display it.
  9483. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9484. * Check your browser for supported MIME types.
  9485. * @param samples Texture samples (default: 1)
  9486. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9487. * @param fileName A name for for the downloaded file.
  9488. * @constructor
  9489. */
  9490. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9491. if (mimeType === void 0) { mimeType = "image/png"; }
  9492. if (samples === void 0) { samples = 1; }
  9493. if (antialiasing === void 0) { antialiasing = false; }
  9494. var width;
  9495. var height;
  9496. //If a precision value is specified
  9497. if (size.precision) {
  9498. width = Math.round(engine.getRenderWidth() * size.precision);
  9499. height = Math.round(width / engine.getAspectRatio(camera));
  9500. size = { width: width, height: height };
  9501. }
  9502. else if (size.width && size.height) {
  9503. width = size.width;
  9504. height = size.height;
  9505. }
  9506. //If passing only width, computing height to keep display canvas ratio.
  9507. else if (size.width && !size.height) {
  9508. width = size.width;
  9509. height = Math.round(width / engine.getAspectRatio(camera));
  9510. size = { width: width, height: height };
  9511. }
  9512. //If passing only height, computing width to keep display canvas ratio.
  9513. else if (size.height && !size.width) {
  9514. height = size.height;
  9515. width = Math.round(height * engine.getAspectRatio(camera));
  9516. size = { width: width, height: height };
  9517. }
  9518. //Assuming here that "size" parameter is a number
  9519. else if (!isNaN(size)) {
  9520. height = size;
  9521. width = size;
  9522. }
  9523. else {
  9524. Tools.Error("Invalid 'size' parameter !");
  9525. return;
  9526. }
  9527. var scene = camera.getScene();
  9528. var previousCamera = null;
  9529. if (scene.activeCamera !== camera) {
  9530. previousCamera = scene.activeCamera;
  9531. scene.activeCamera = camera;
  9532. }
  9533. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9534. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9535. texture.renderList = null;
  9536. texture.samples = samples;
  9537. if (antialiasing) {
  9538. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9539. }
  9540. texture.onAfterRenderObservable.add(function () {
  9541. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9542. });
  9543. scene.incrementRenderId();
  9544. scene.resetCachedMaterial();
  9545. texture.render(true);
  9546. texture.dispose();
  9547. if (previousCamera) {
  9548. scene.activeCamera = previousCamera;
  9549. }
  9550. camera.getProjectionMatrix(true); // Force cache refresh;
  9551. };
  9552. // XHR response validator for local file scenario
  9553. Tools.ValidateXHRData = function (xhr, dataType) {
  9554. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9555. if (dataType === void 0) { dataType = 7; }
  9556. try {
  9557. if (dataType & 1) {
  9558. if (xhr.responseText && xhr.responseText.length > 0) {
  9559. return true;
  9560. }
  9561. else if (dataType === 1) {
  9562. return false;
  9563. }
  9564. }
  9565. if (dataType & 2) {
  9566. // Check header width and height since there is no "TGA" magic number
  9567. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9568. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9569. return true;
  9570. }
  9571. else if (dataType === 2) {
  9572. return false;
  9573. }
  9574. }
  9575. if (dataType & 4) {
  9576. // Check for the "DDS" magic number
  9577. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9578. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9579. return true;
  9580. }
  9581. else {
  9582. return false;
  9583. }
  9584. }
  9585. }
  9586. catch (e) {
  9587. // Global protection
  9588. }
  9589. return false;
  9590. };
  9591. /**
  9592. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9593. * Be aware Math.random() could cause collisions, but:
  9594. * "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"
  9595. */
  9596. Tools.RandomId = function () {
  9597. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9598. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9599. return v.toString(16);
  9600. });
  9601. };
  9602. /**
  9603. * Test if the given uri is a base64 string.
  9604. * @param uri The uri to test
  9605. * @return True if the uri is a base64 string or false otherwise.
  9606. */
  9607. Tools.IsBase64 = function (uri) {
  9608. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9609. };
  9610. /**
  9611. * Decode the given base64 uri.
  9612. * @param uri The uri to decode
  9613. * @return The decoded base64 data.
  9614. */
  9615. Tools.DecodeBase64 = function (uri) {
  9616. var decodedString = atob(uri.split(",")[1]);
  9617. var bufferLength = decodedString.length;
  9618. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9619. for (var i = 0; i < bufferLength; i++) {
  9620. bufferView[i] = decodedString.charCodeAt(i);
  9621. }
  9622. return bufferView.buffer;
  9623. };
  9624. Object.defineProperty(Tools, "NoneLogLevel", {
  9625. get: function () {
  9626. return Tools._NoneLogLevel;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Tools, "MessageLogLevel", {
  9632. get: function () {
  9633. return Tools._MessageLogLevel;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Tools, "WarningLogLevel", {
  9639. get: function () {
  9640. return Tools._WarningLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "ErrorLogLevel", {
  9646. get: function () {
  9647. return Tools._ErrorLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "AllLogLevel", {
  9653. get: function () {
  9654. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Tools._AddLogEntry = function (entry) {
  9660. Tools._LogCache = entry + Tools._LogCache;
  9661. if (Tools.OnNewCacheEntry) {
  9662. Tools.OnNewCacheEntry(entry);
  9663. }
  9664. };
  9665. Tools._FormatMessage = function (message) {
  9666. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9667. var date = new Date();
  9668. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9669. };
  9670. Tools._LogDisabled = function (message) {
  9671. // nothing to do
  9672. };
  9673. Tools._LogEnabled = function (message) {
  9674. var formattedMessage = Tools._FormatMessage(message);
  9675. console.log("BJS - " + formattedMessage);
  9676. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9677. Tools._AddLogEntry(entry);
  9678. };
  9679. Tools._WarnDisabled = function (message) {
  9680. // nothing to do
  9681. };
  9682. Tools._WarnEnabled = function (message) {
  9683. var formattedMessage = Tools._FormatMessage(message);
  9684. console.warn("BJS - " + formattedMessage);
  9685. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9686. Tools._AddLogEntry(entry);
  9687. };
  9688. Tools._ErrorDisabled = function (message) {
  9689. // nothing to do
  9690. };
  9691. Tools._ErrorEnabled = function (message) {
  9692. Tools.errorsCount++;
  9693. var formattedMessage = Tools._FormatMessage(message);
  9694. console.error("BJS - " + formattedMessage);
  9695. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9696. Tools._AddLogEntry(entry);
  9697. };
  9698. Object.defineProperty(Tools, "LogCache", {
  9699. get: function () {
  9700. return Tools._LogCache;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Tools.ClearLogCache = function () {
  9706. Tools._LogCache = "";
  9707. Tools.errorsCount = 0;
  9708. };
  9709. Object.defineProperty(Tools, "LogLevels", {
  9710. set: function (level) {
  9711. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9712. Tools.Log = Tools._LogEnabled;
  9713. }
  9714. else {
  9715. Tools.Log = Tools._LogDisabled;
  9716. }
  9717. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9718. Tools.Warn = Tools._WarnEnabled;
  9719. }
  9720. else {
  9721. Tools.Warn = Tools._WarnDisabled;
  9722. }
  9723. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9724. Tools.Error = Tools._ErrorEnabled;
  9725. }
  9726. else {
  9727. Tools.Error = Tools._ErrorDisabled;
  9728. }
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Tools.IsWindowObjectExist = function () {
  9734. return (typeof window) !== "undefined";
  9735. };
  9736. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9737. get: function () {
  9738. return Tools._PerformanceNoneLogLevel;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9744. get: function () {
  9745. return Tools._PerformanceUserMarkLogLevel;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceConsoleLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9758. set: function (level) {
  9759. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9760. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9761. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9762. return;
  9763. }
  9764. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9765. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9766. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9767. return;
  9768. }
  9769. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9770. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9776. };
  9777. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9778. };
  9779. Tools._StartUserMark = function (counterName, condition) {
  9780. if (condition === void 0) { condition = true; }
  9781. if (!Tools._performance) {
  9782. if (!Tools.IsWindowObjectExist()) {
  9783. return;
  9784. }
  9785. Tools._performance = window.performance;
  9786. }
  9787. if (!condition || !Tools._performance.mark) {
  9788. return;
  9789. }
  9790. Tools._performance.mark(counterName + "-Begin");
  9791. };
  9792. Tools._EndUserMark = function (counterName, condition) {
  9793. if (condition === void 0) { condition = true; }
  9794. if (!condition || !Tools._performance.mark) {
  9795. return;
  9796. }
  9797. Tools._performance.mark(counterName + "-End");
  9798. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9799. };
  9800. Tools._StartPerformanceConsole = function (counterName, condition) {
  9801. if (condition === void 0) { condition = true; }
  9802. if (!condition) {
  9803. return;
  9804. }
  9805. Tools._StartUserMark(counterName, condition);
  9806. if (console.time) {
  9807. console.time(counterName);
  9808. }
  9809. };
  9810. Tools._EndPerformanceConsole = function (counterName, condition) {
  9811. if (condition === void 0) { condition = true; }
  9812. if (!condition) {
  9813. return;
  9814. }
  9815. Tools._EndUserMark(counterName, condition);
  9816. if (console.time) {
  9817. console.timeEnd(counterName);
  9818. }
  9819. };
  9820. Object.defineProperty(Tools, "Now", {
  9821. get: function () {
  9822. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9823. return window.performance.now();
  9824. }
  9825. return Date.now();
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. /**
  9831. * This method will return the name of the class used to create the instance of the given object.
  9832. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9833. * @param object the object to get the class name from
  9834. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9835. */
  9836. Tools.GetClassName = function (object, isType) {
  9837. if (isType === void 0) { isType = false; }
  9838. var name = null;
  9839. if (!isType && object.getClassName) {
  9840. name = object.getClassName();
  9841. }
  9842. else {
  9843. if (object instanceof Object) {
  9844. var classObj = isType ? object : Object.getPrototypeOf(object);
  9845. name = classObj.constructor["__bjsclassName__"];
  9846. }
  9847. if (!name) {
  9848. name = typeof object;
  9849. }
  9850. }
  9851. return name;
  9852. };
  9853. Tools.First = function (array, predicate) {
  9854. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9855. var el = array_1[_i];
  9856. if (predicate(el)) {
  9857. return el;
  9858. }
  9859. }
  9860. return null;
  9861. };
  9862. /**
  9863. * This method will return the name of the full name of the class, including its owning module (if any).
  9864. * 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).
  9865. * @param object the object to get the class name from
  9866. * @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.
  9867. */
  9868. Tools.getFullClassName = function (object, isType) {
  9869. if (isType === void 0) { isType = false; }
  9870. var className = null;
  9871. var moduleName = null;
  9872. if (!isType && object.getClassName) {
  9873. className = object.getClassName();
  9874. }
  9875. else {
  9876. if (object instanceof Object) {
  9877. var classObj = isType ? object : Object.getPrototypeOf(object);
  9878. className = classObj.constructor["__bjsclassName__"];
  9879. moduleName = classObj.constructor["__bjsmoduleName__"];
  9880. }
  9881. if (!className) {
  9882. className = typeof object;
  9883. }
  9884. }
  9885. if (!className) {
  9886. return null;
  9887. }
  9888. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9889. };
  9890. /**
  9891. * 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.
  9892. * @param array
  9893. */
  9894. Tools.arrayOrStringFeeder = function (array) {
  9895. return function (index) {
  9896. if (index >= array.length) {
  9897. return null;
  9898. }
  9899. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9900. if (val && val.getHashCode) {
  9901. val = val.getHashCode();
  9902. }
  9903. if (typeof val === "string") {
  9904. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9905. }
  9906. return val;
  9907. };
  9908. };
  9909. /**
  9910. * Compute the hashCode of a stream of number
  9911. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9912. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9913. * @return the hash code computed
  9914. */
  9915. Tools.hashCodeFromStream = function (feeder) {
  9916. // Based from here: http://stackoverflow.com/a/7616484/802124
  9917. var hash = 0;
  9918. var index = 0;
  9919. var chr = feeder(index++);
  9920. while (chr != null) {
  9921. hash = ((hash << 5) - hash) + chr;
  9922. hash |= 0; // Convert to 32bit integer
  9923. chr = feeder(index++);
  9924. }
  9925. return hash;
  9926. };
  9927. /**
  9928. * Returns a promise that resolves after the given amount of time.
  9929. * @param delay Number of milliseconds to delay
  9930. * @returns Promise that resolves after the given amount of time
  9931. */
  9932. Tools.DelayAsync = function (delay) {
  9933. return new Promise(function (resolve) {
  9934. setTimeout(function () {
  9935. resolve();
  9936. }, delay);
  9937. });
  9938. };
  9939. /**
  9940. * Gets the current gradient from an array of IValueGradient
  9941. * @param ratio defines the current ratio to get
  9942. * @param gradients defines the array of IValueGradient
  9943. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9944. */
  9945. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9946. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9947. var currentGradient = gradients[gradientIndex];
  9948. var nextGradient = gradients[gradientIndex + 1];
  9949. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9950. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9951. updateFunc(currentGradient, nextGradient, scale);
  9952. }
  9953. }
  9954. };
  9955. Tools.BaseUrl = "";
  9956. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9957. /**
  9958. * Default behaviour for cors in the application.
  9959. * It can be a string if the expected behavior is identical in the entire app.
  9960. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9961. */
  9962. Tools.CorsBehavior = "anonymous";
  9963. Tools.UseFallbackTexture = true;
  9964. /**
  9965. * Use this object to register external classes like custom textures or material
  9966. * to allow the laoders to instantiate them
  9967. */
  9968. Tools.RegisteredExternalClasses = {};
  9969. // Used in case of a texture loading problem
  9970. 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";
  9971. Tools._tmpFloatArray = new Float32Array(1);
  9972. Tools.PreprocessUrl = function (url) {
  9973. return url;
  9974. };
  9975. // Logs
  9976. Tools._NoneLogLevel = 0;
  9977. Tools._MessageLogLevel = 1;
  9978. Tools._WarningLogLevel = 2;
  9979. Tools._ErrorLogLevel = 4;
  9980. Tools._LogCache = "";
  9981. Tools.errorsCount = 0;
  9982. Tools.Log = Tools._LogEnabled;
  9983. Tools.Warn = Tools._WarnEnabled;
  9984. Tools.Error = Tools._ErrorEnabled;
  9985. // Performances
  9986. Tools._PerformanceNoneLogLevel = 0;
  9987. Tools._PerformanceUserMarkLogLevel = 1;
  9988. Tools._PerformanceConsoleLogLevel = 2;
  9989. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9990. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9991. return Tools;
  9992. }());
  9993. BABYLON.Tools = Tools;
  9994. /**
  9995. * This class is used to track a performance counter which is number based.
  9996. * The user has access to many properties which give statistics of different nature
  9997. *
  9998. * The implementer can track two kinds of Performance Counter: time and count
  9999. * 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.
  10000. * 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.
  10001. */
  10002. var PerfCounter = /** @class */ (function () {
  10003. function PerfCounter() {
  10004. this._startMonitoringTime = 0;
  10005. this._min = 0;
  10006. this._max = 0;
  10007. this._average = 0;
  10008. this._lastSecAverage = 0;
  10009. this._current = 0;
  10010. this._totalValueCount = 0;
  10011. this._totalAccumulated = 0;
  10012. this._lastSecAccumulated = 0;
  10013. this._lastSecTime = 0;
  10014. this._lastSecValueCount = 0;
  10015. }
  10016. Object.defineProperty(PerfCounter.prototype, "min", {
  10017. /**
  10018. * Returns the smallest value ever
  10019. */
  10020. get: function () {
  10021. return this._min;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(PerfCounter.prototype, "max", {
  10027. /**
  10028. * Returns the biggest value ever
  10029. */
  10030. get: function () {
  10031. return this._max;
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(PerfCounter.prototype, "average", {
  10037. /**
  10038. * Returns the average value since the performance counter is running
  10039. */
  10040. get: function () {
  10041. return this._average;
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10047. /**
  10048. * Returns the average value of the last second the counter was monitored
  10049. */
  10050. get: function () {
  10051. return this._lastSecAverage;
  10052. },
  10053. enumerable: true,
  10054. configurable: true
  10055. });
  10056. Object.defineProperty(PerfCounter.prototype, "current", {
  10057. /**
  10058. * Returns the current value
  10059. */
  10060. get: function () {
  10061. return this._current;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(PerfCounter.prototype, "total", {
  10067. get: function () {
  10068. return this._totalAccumulated;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(PerfCounter.prototype, "count", {
  10074. get: function () {
  10075. return this._totalValueCount;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. /**
  10081. * Call this method to start monitoring a new frame.
  10082. * 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.
  10083. */
  10084. PerfCounter.prototype.fetchNewFrame = function () {
  10085. this._totalValueCount++;
  10086. this._current = 0;
  10087. this._lastSecValueCount++;
  10088. };
  10089. /**
  10090. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10091. * @param newCount the count value to add to the monitored count
  10092. * @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.
  10093. */
  10094. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10095. if (!PerfCounter.Enabled) {
  10096. return;
  10097. }
  10098. this._current += newCount;
  10099. if (fetchResult) {
  10100. this._fetchResult();
  10101. }
  10102. };
  10103. /**
  10104. * Start monitoring this performance counter
  10105. */
  10106. PerfCounter.prototype.beginMonitoring = function () {
  10107. if (!PerfCounter.Enabled) {
  10108. return;
  10109. }
  10110. this._startMonitoringTime = Tools.Now;
  10111. };
  10112. /**
  10113. * Compute the time lapsed since the previous beginMonitoring() call.
  10114. * @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
  10115. */
  10116. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10117. if (newFrame === void 0) { newFrame = true; }
  10118. if (!PerfCounter.Enabled) {
  10119. return;
  10120. }
  10121. if (newFrame) {
  10122. this.fetchNewFrame();
  10123. }
  10124. var currentTime = Tools.Now;
  10125. this._current = currentTime - this._startMonitoringTime;
  10126. if (newFrame) {
  10127. this._fetchResult();
  10128. }
  10129. };
  10130. PerfCounter.prototype._fetchResult = function () {
  10131. this._totalAccumulated += this._current;
  10132. this._lastSecAccumulated += this._current;
  10133. // Min/Max update
  10134. this._min = Math.min(this._min, this._current);
  10135. this._max = Math.max(this._max, this._current);
  10136. this._average = this._totalAccumulated / this._totalValueCount;
  10137. // Reset last sec?
  10138. var now = Tools.Now;
  10139. if ((now - this._lastSecTime) > 1000) {
  10140. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10141. this._lastSecTime = now;
  10142. this._lastSecAccumulated = 0;
  10143. this._lastSecValueCount = 0;
  10144. }
  10145. };
  10146. PerfCounter.Enabled = true;
  10147. return PerfCounter;
  10148. }());
  10149. BABYLON.PerfCounter = PerfCounter;
  10150. /**
  10151. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10152. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10153. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10154. * @param name The name of the class, case should be preserved
  10155. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10156. */
  10157. function className(name, module) {
  10158. return function (target) {
  10159. target["__bjsclassName__"] = name;
  10160. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10161. };
  10162. }
  10163. BABYLON.className = className;
  10164. /**
  10165. * An implementation of a loop for asynchronous functions.
  10166. */
  10167. var AsyncLoop = /** @class */ (function () {
  10168. /**
  10169. * Constroctor.
  10170. * @param iterations the number of iterations.
  10171. * @param _fn the function to run each iteration
  10172. * @param _successCallback the callback that will be called upon succesful execution
  10173. * @param offset starting offset.
  10174. */
  10175. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10176. if (offset === void 0) { offset = 0; }
  10177. this.iterations = iterations;
  10178. this._fn = _fn;
  10179. this._successCallback = _successCallback;
  10180. this.index = offset - 1;
  10181. this._done = false;
  10182. }
  10183. /**
  10184. * Execute the next iteration. Must be called after the last iteration was finished.
  10185. */
  10186. AsyncLoop.prototype.executeNext = function () {
  10187. if (!this._done) {
  10188. if (this.index + 1 < this.iterations) {
  10189. ++this.index;
  10190. this._fn(this);
  10191. }
  10192. else {
  10193. this.breakLoop();
  10194. }
  10195. }
  10196. };
  10197. /**
  10198. * Break the loop and run the success callback.
  10199. */
  10200. AsyncLoop.prototype.breakLoop = function () {
  10201. this._done = true;
  10202. this._successCallback();
  10203. };
  10204. /**
  10205. * Helper function
  10206. */
  10207. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10208. if (offset === void 0) { offset = 0; }
  10209. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10210. loop.executeNext();
  10211. return loop;
  10212. };
  10213. /**
  10214. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10215. * @param iterations total number of iterations
  10216. * @param syncedIterations number of synchronous iterations in each async iteration.
  10217. * @param fn the function to call each iteration.
  10218. * @param callback a success call back that will be called when iterating stops.
  10219. * @param breakFunction a break condition (optional)
  10220. * @param timeout timeout settings for the setTimeout function. default - 0.
  10221. * @constructor
  10222. */
  10223. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10224. if (timeout === void 0) { timeout = 0; }
  10225. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10226. if (breakFunction && breakFunction())
  10227. loop.breakLoop();
  10228. else {
  10229. setTimeout(function () {
  10230. for (var i = 0; i < syncedIterations; ++i) {
  10231. var iteration = (loop.index * syncedIterations) + i;
  10232. if (iteration >= iterations)
  10233. break;
  10234. fn(iteration);
  10235. if (breakFunction && breakFunction()) {
  10236. loop.breakLoop();
  10237. break;
  10238. }
  10239. }
  10240. loop.executeNext();
  10241. }, timeout);
  10242. }
  10243. }, callback);
  10244. };
  10245. return AsyncLoop;
  10246. }());
  10247. BABYLON.AsyncLoop = AsyncLoop;
  10248. })(BABYLON || (BABYLON = {}));
  10249. //# sourceMappingURL=babylon.tools.js.map
  10250. var BABYLON;
  10251. (function (BABYLON) {
  10252. var PromiseStates;
  10253. (function (PromiseStates) {
  10254. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10255. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10256. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10257. })(PromiseStates || (PromiseStates = {}));
  10258. var FulFillmentAgregator = /** @class */ (function () {
  10259. function FulFillmentAgregator() {
  10260. this.count = 0;
  10261. this.target = 0;
  10262. this.results = [];
  10263. }
  10264. return FulFillmentAgregator;
  10265. }());
  10266. var InternalPromise = /** @class */ (function () {
  10267. function InternalPromise(resolver) {
  10268. var _this = this;
  10269. this._state = PromiseStates.Pending;
  10270. this._children = new Array();
  10271. this._rejectWasConsumed = false;
  10272. if (!resolver) {
  10273. return;
  10274. }
  10275. try {
  10276. resolver(function (value) {
  10277. _this._resolve(value);
  10278. }, function (reason) {
  10279. _this._reject(reason);
  10280. });
  10281. }
  10282. catch (e) {
  10283. this._reject(e);
  10284. }
  10285. }
  10286. Object.defineProperty(InternalPromise.prototype, "_result", {
  10287. get: function () {
  10288. return this._resultValue;
  10289. },
  10290. set: function (value) {
  10291. this._resultValue = value;
  10292. if (this._parent && this._parent._result === undefined) {
  10293. this._parent._result = value;
  10294. }
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. InternalPromise.prototype.catch = function (onRejected) {
  10300. return this.then(undefined, onRejected);
  10301. };
  10302. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10303. var _this = this;
  10304. var newPromise = new InternalPromise();
  10305. newPromise._onFulfilled = onFulfilled;
  10306. newPromise._onRejected = onRejected;
  10307. // Composition
  10308. this._children.push(newPromise);
  10309. newPromise._parent = this;
  10310. if (this._state !== PromiseStates.Pending) {
  10311. BABYLON.Tools.SetImmediate(function () {
  10312. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10313. var returnedValue = newPromise._resolve(_this._result);
  10314. if (returnedValue !== undefined && returnedValue !== null) {
  10315. if (returnedValue._state !== undefined) {
  10316. var returnedPromise = returnedValue;
  10317. newPromise._children.push(returnedPromise);
  10318. returnedPromise._parent = newPromise;
  10319. newPromise = returnedPromise;
  10320. }
  10321. else {
  10322. newPromise._result = returnedValue;
  10323. }
  10324. }
  10325. }
  10326. else {
  10327. newPromise._reject(_this._reason);
  10328. }
  10329. });
  10330. }
  10331. return newPromise;
  10332. };
  10333. InternalPromise.prototype._moveChildren = function (children) {
  10334. var _this = this;
  10335. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10336. this._children.forEach(function (child) {
  10337. child._parent = _this;
  10338. });
  10339. if (this._state === PromiseStates.Fulfilled) {
  10340. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10341. var child = _b[_i];
  10342. child._resolve(this._result);
  10343. }
  10344. }
  10345. else if (this._state === PromiseStates.Rejected) {
  10346. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10347. var child = _d[_c];
  10348. child._reject(this._reason);
  10349. }
  10350. }
  10351. var _a;
  10352. };
  10353. InternalPromise.prototype._resolve = function (value) {
  10354. try {
  10355. this._state = PromiseStates.Fulfilled;
  10356. var returnedValue = null;
  10357. if (this._onFulfilled) {
  10358. returnedValue = this._onFulfilled(value);
  10359. }
  10360. if (returnedValue !== undefined && returnedValue !== null) {
  10361. if (returnedValue._state !== undefined) {
  10362. // Transmit children
  10363. var returnedPromise = returnedValue;
  10364. returnedPromise._parent = this;
  10365. returnedPromise._moveChildren(this._children);
  10366. value = returnedPromise._result;
  10367. }
  10368. else {
  10369. value = returnedValue;
  10370. }
  10371. }
  10372. this._result = value;
  10373. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10374. var child = _a[_i];
  10375. child._resolve(value);
  10376. }
  10377. this._children.length = 0;
  10378. delete this._onFulfilled;
  10379. delete this._onRejected;
  10380. }
  10381. catch (e) {
  10382. this._reject(e, true);
  10383. }
  10384. };
  10385. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10386. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10387. this._state = PromiseStates.Rejected;
  10388. this._reason = reason;
  10389. if (this._onRejected && !onLocalThrow) {
  10390. try {
  10391. this._onRejected(reason);
  10392. this._rejectWasConsumed = true;
  10393. }
  10394. catch (e) {
  10395. reason = e;
  10396. }
  10397. }
  10398. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10399. var child = _a[_i];
  10400. if (this._rejectWasConsumed) {
  10401. child._resolve(null);
  10402. }
  10403. else {
  10404. child._reject(reason);
  10405. }
  10406. }
  10407. this._children.length = 0;
  10408. delete this._onFulfilled;
  10409. delete this._onRejected;
  10410. };
  10411. InternalPromise.resolve = function (value) {
  10412. var newPromise = new InternalPromise();
  10413. newPromise._resolve(value);
  10414. return newPromise;
  10415. };
  10416. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10417. promise.then(function (value) {
  10418. agregator.results[index] = value;
  10419. agregator.count++;
  10420. if (agregator.count === agregator.target) {
  10421. agregator.rootPromise._resolve(agregator.results);
  10422. }
  10423. return null;
  10424. }, function (reason) {
  10425. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10426. agregator.rootPromise._reject(reason);
  10427. }
  10428. });
  10429. };
  10430. InternalPromise.all = function (promises) {
  10431. var newPromise = new InternalPromise();
  10432. var agregator = new FulFillmentAgregator();
  10433. agregator.target = promises.length;
  10434. agregator.rootPromise = newPromise;
  10435. if (promises.length) {
  10436. for (var index = 0; index < promises.length; index++) {
  10437. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10438. }
  10439. }
  10440. else {
  10441. newPromise._resolve([]);
  10442. }
  10443. return newPromise;
  10444. };
  10445. InternalPromise.race = function (promises) {
  10446. var newPromise = new InternalPromise();
  10447. if (promises.length) {
  10448. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10449. var promise = promises_1[_i];
  10450. promise.then(function (value) {
  10451. if (newPromise) {
  10452. newPromise._resolve(value);
  10453. newPromise = null;
  10454. }
  10455. return null;
  10456. }, function (reason) {
  10457. if (newPromise) {
  10458. newPromise._reject(reason);
  10459. newPromise = null;
  10460. }
  10461. });
  10462. }
  10463. }
  10464. return newPromise;
  10465. };
  10466. return InternalPromise;
  10467. }());
  10468. /**
  10469. * Helper class that provides a small promise polyfill
  10470. */
  10471. var PromisePolyfill = /** @class */ (function () {
  10472. function PromisePolyfill() {
  10473. }
  10474. /**
  10475. * Static function used to check if the polyfill is required
  10476. * If this is the case then the function will inject the polyfill to window.Promise
  10477. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10478. */
  10479. PromisePolyfill.Apply = function (force) {
  10480. if (force === void 0) { force = false; }
  10481. if (force || typeof Promise === 'undefined') {
  10482. var root = window;
  10483. root.Promise = InternalPromise;
  10484. }
  10485. };
  10486. return PromisePolyfill;
  10487. }());
  10488. BABYLON.PromisePolyfill = PromisePolyfill;
  10489. })(BABYLON || (BABYLON = {}));
  10490. //# sourceMappingURL=babylon.promise.js.map
  10491. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10492. var BABYLON;
  10493. (function (BABYLON) {
  10494. /**
  10495. * Helper class to push actions to a pool of workers.
  10496. */
  10497. var WorkerPool = /** @class */ (function () {
  10498. /**
  10499. * Constructor
  10500. * @param workers Array of workers to use for actions
  10501. */
  10502. function WorkerPool(workers) {
  10503. this._pendingActions = new Array();
  10504. this._workerInfos = workers.map(function (worker) { return ({
  10505. worker: worker,
  10506. active: false
  10507. }); });
  10508. }
  10509. /**
  10510. * Terminates all workers and clears any pending actions.
  10511. */
  10512. WorkerPool.prototype.dispose = function () {
  10513. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10514. var workerInfo = _a[_i];
  10515. workerInfo.worker.terminate();
  10516. }
  10517. delete this._workerInfos;
  10518. delete this._pendingActions;
  10519. };
  10520. /**
  10521. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10522. * pended until a worker has completed its action.
  10523. * @param action The action to perform. Call onComplete when the action is complete.
  10524. */
  10525. WorkerPool.prototype.push = function (action) {
  10526. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10527. var workerInfo = _a[_i];
  10528. if (!workerInfo.active) {
  10529. this._execute(workerInfo, action);
  10530. return;
  10531. }
  10532. }
  10533. this._pendingActions.push(action);
  10534. };
  10535. WorkerPool.prototype._execute = function (workerInfo, action) {
  10536. var _this = this;
  10537. workerInfo.active = true;
  10538. action(workerInfo.worker, function () {
  10539. workerInfo.active = false;
  10540. var nextAction = _this._pendingActions.shift();
  10541. if (nextAction) {
  10542. _this._execute(workerInfo, nextAction);
  10543. }
  10544. });
  10545. };
  10546. return WorkerPool;
  10547. }());
  10548. BABYLON.WorkerPool = WorkerPool;
  10549. })(BABYLON || (BABYLON = {}));
  10550. //# sourceMappingURL=babylon.workerPool.js.map
  10551. var BABYLON;
  10552. (function (BABYLON) {
  10553. /**
  10554. * @hidden
  10555. **/
  10556. var _AlphaState = /** @class */ (function () {
  10557. /**
  10558. * Initializes the state.
  10559. */
  10560. function _AlphaState() {
  10561. this._isAlphaBlendDirty = false;
  10562. this._isBlendFunctionParametersDirty = false;
  10563. this._isBlendEquationParametersDirty = false;
  10564. this._isBlendConstantsDirty = false;
  10565. this._alphaBlend = false;
  10566. this._blendFunctionParameters = new Array(4);
  10567. this._blendEquationParameters = new Array(2);
  10568. this._blendConstants = new Array(4);
  10569. this.reset();
  10570. }
  10571. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10572. get: function () {
  10573. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10574. },
  10575. enumerable: true,
  10576. configurable: true
  10577. });
  10578. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10579. get: function () {
  10580. return this._alphaBlend;
  10581. },
  10582. set: function (value) {
  10583. if (this._alphaBlend === value) {
  10584. return;
  10585. }
  10586. this._alphaBlend = value;
  10587. this._isAlphaBlendDirty = true;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10593. if (this._blendConstants[0] === r &&
  10594. this._blendConstants[1] === g &&
  10595. this._blendConstants[2] === b &&
  10596. this._blendConstants[3] === a) {
  10597. return;
  10598. }
  10599. this._blendConstants[0] = r;
  10600. this._blendConstants[1] = g;
  10601. this._blendConstants[2] = b;
  10602. this._blendConstants[3] = a;
  10603. this._isBlendConstantsDirty = true;
  10604. };
  10605. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10606. if (this._blendFunctionParameters[0] === value0 &&
  10607. this._blendFunctionParameters[1] === value1 &&
  10608. this._blendFunctionParameters[2] === value2 &&
  10609. this._blendFunctionParameters[3] === value3) {
  10610. return;
  10611. }
  10612. this._blendFunctionParameters[0] = value0;
  10613. this._blendFunctionParameters[1] = value1;
  10614. this._blendFunctionParameters[2] = value2;
  10615. this._blendFunctionParameters[3] = value3;
  10616. this._isBlendFunctionParametersDirty = true;
  10617. };
  10618. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10619. if (this._blendEquationParameters[0] === rgb &&
  10620. this._blendEquationParameters[1] === alpha) {
  10621. return;
  10622. }
  10623. this._blendEquationParameters[0] = rgb;
  10624. this._blendEquationParameters[1] = alpha;
  10625. this._isBlendEquationParametersDirty = true;
  10626. };
  10627. _AlphaState.prototype.reset = function () {
  10628. this._alphaBlend = false;
  10629. this._blendFunctionParameters[0] = null;
  10630. this._blendFunctionParameters[1] = null;
  10631. this._blendFunctionParameters[2] = null;
  10632. this._blendFunctionParameters[3] = null;
  10633. this._blendEquationParameters[0] = null;
  10634. this._blendEquationParameters[1] = null;
  10635. this._blendConstants[0] = null;
  10636. this._blendConstants[1] = null;
  10637. this._blendConstants[2] = null;
  10638. this._blendConstants[3] = null;
  10639. this._isAlphaBlendDirty = true;
  10640. this._isBlendFunctionParametersDirty = false;
  10641. this._isBlendEquationParametersDirty = false;
  10642. this._isBlendConstantsDirty = false;
  10643. };
  10644. _AlphaState.prototype.apply = function (gl) {
  10645. if (!this.isDirty) {
  10646. return;
  10647. }
  10648. // Alpha blend
  10649. if (this._isAlphaBlendDirty) {
  10650. if (this._alphaBlend) {
  10651. gl.enable(gl.BLEND);
  10652. }
  10653. else {
  10654. gl.disable(gl.BLEND);
  10655. }
  10656. this._isAlphaBlendDirty = false;
  10657. }
  10658. // Alpha function
  10659. if (this._isBlendFunctionParametersDirty) {
  10660. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10661. this._isBlendFunctionParametersDirty = false;
  10662. }
  10663. // Alpha equation
  10664. if (this._isBlendEquationParametersDirty) {
  10665. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10666. this._isBlendEquationParametersDirty = false;
  10667. }
  10668. // Constants
  10669. if (this._isBlendConstantsDirty) {
  10670. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10671. this._isBlendConstantsDirty = false;
  10672. }
  10673. };
  10674. return _AlphaState;
  10675. }());
  10676. BABYLON._AlphaState = _AlphaState;
  10677. })(BABYLON || (BABYLON = {}));
  10678. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10679. var BABYLON;
  10680. (function (BABYLON) {
  10681. /**
  10682. * @hidden
  10683. **/
  10684. var _DepthCullingState = /** @class */ (function () {
  10685. /**
  10686. * Initializes the state.
  10687. */
  10688. function _DepthCullingState() {
  10689. this._isDepthTestDirty = false;
  10690. this._isDepthMaskDirty = false;
  10691. this._isDepthFuncDirty = false;
  10692. this._isCullFaceDirty = false;
  10693. this._isCullDirty = false;
  10694. this._isZOffsetDirty = false;
  10695. this._isFrontFaceDirty = false;
  10696. this.reset();
  10697. }
  10698. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10699. get: function () {
  10700. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10706. get: function () {
  10707. return this._zOffset;
  10708. },
  10709. set: function (value) {
  10710. if (this._zOffset === value) {
  10711. return;
  10712. }
  10713. this._zOffset = value;
  10714. this._isZOffsetDirty = true;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10720. get: function () {
  10721. return this._cullFace;
  10722. },
  10723. set: function (value) {
  10724. if (this._cullFace === value) {
  10725. return;
  10726. }
  10727. this._cullFace = value;
  10728. this._isCullFaceDirty = true;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10734. get: function () {
  10735. return this._cull;
  10736. },
  10737. set: function (value) {
  10738. if (this._cull === value) {
  10739. return;
  10740. }
  10741. this._cull = value;
  10742. this._isCullDirty = true;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10748. get: function () {
  10749. return this._depthFunc;
  10750. },
  10751. set: function (value) {
  10752. if (this._depthFunc === value) {
  10753. return;
  10754. }
  10755. this._depthFunc = value;
  10756. this._isDepthFuncDirty = true;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10762. get: function () {
  10763. return this._depthMask;
  10764. },
  10765. set: function (value) {
  10766. if (this._depthMask === value) {
  10767. return;
  10768. }
  10769. this._depthMask = value;
  10770. this._isDepthMaskDirty = true;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10776. get: function () {
  10777. return this._depthTest;
  10778. },
  10779. set: function (value) {
  10780. if (this._depthTest === value) {
  10781. return;
  10782. }
  10783. this._depthTest = value;
  10784. this._isDepthTestDirty = true;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10790. get: function () {
  10791. return this._frontFace;
  10792. },
  10793. set: function (value) {
  10794. if (this._frontFace === value) {
  10795. return;
  10796. }
  10797. this._frontFace = value;
  10798. this._isFrontFaceDirty = true;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. _DepthCullingState.prototype.reset = function () {
  10804. this._depthMask = true;
  10805. this._depthTest = true;
  10806. this._depthFunc = null;
  10807. this._cullFace = null;
  10808. this._cull = null;
  10809. this._zOffset = 0;
  10810. this._frontFace = null;
  10811. this._isDepthTestDirty = true;
  10812. this._isDepthMaskDirty = true;
  10813. this._isDepthFuncDirty = false;
  10814. this._isCullFaceDirty = false;
  10815. this._isCullDirty = false;
  10816. this._isZOffsetDirty = false;
  10817. this._isFrontFaceDirty = false;
  10818. };
  10819. _DepthCullingState.prototype.apply = function (gl) {
  10820. if (!this.isDirty) {
  10821. return;
  10822. }
  10823. // Cull
  10824. if (this._isCullDirty) {
  10825. if (this.cull) {
  10826. gl.enable(gl.CULL_FACE);
  10827. }
  10828. else {
  10829. gl.disable(gl.CULL_FACE);
  10830. }
  10831. this._isCullDirty = false;
  10832. }
  10833. // Cull face
  10834. if (this._isCullFaceDirty) {
  10835. gl.cullFace(this.cullFace);
  10836. this._isCullFaceDirty = false;
  10837. }
  10838. // Depth mask
  10839. if (this._isDepthMaskDirty) {
  10840. gl.depthMask(this.depthMask);
  10841. this._isDepthMaskDirty = false;
  10842. }
  10843. // Depth test
  10844. if (this._isDepthTestDirty) {
  10845. if (this.depthTest) {
  10846. gl.enable(gl.DEPTH_TEST);
  10847. }
  10848. else {
  10849. gl.disable(gl.DEPTH_TEST);
  10850. }
  10851. this._isDepthTestDirty = false;
  10852. }
  10853. // Depth func
  10854. if (this._isDepthFuncDirty) {
  10855. gl.depthFunc(this.depthFunc);
  10856. this._isDepthFuncDirty = false;
  10857. }
  10858. // zOffset
  10859. if (this._isZOffsetDirty) {
  10860. if (this.zOffset) {
  10861. gl.enable(gl.POLYGON_OFFSET_FILL);
  10862. gl.polygonOffset(this.zOffset, 0);
  10863. }
  10864. else {
  10865. gl.disable(gl.POLYGON_OFFSET_FILL);
  10866. }
  10867. this._isZOffsetDirty = false;
  10868. }
  10869. // Front face
  10870. if (this._isFrontFaceDirty) {
  10871. gl.frontFace(this.frontFace);
  10872. this._isFrontFaceDirty = false;
  10873. }
  10874. };
  10875. return _DepthCullingState;
  10876. }());
  10877. BABYLON._DepthCullingState = _DepthCullingState;
  10878. })(BABYLON || (BABYLON = {}));
  10879. //# sourceMappingURL=babylon.depthCullingState.js.map
  10880. var BABYLON;
  10881. (function (BABYLON) {
  10882. /**
  10883. * @hidden
  10884. **/
  10885. var _StencilState = /** @class */ (function () {
  10886. function _StencilState() {
  10887. this._isStencilTestDirty = false;
  10888. this._isStencilMaskDirty = false;
  10889. this._isStencilFuncDirty = false;
  10890. this._isStencilOpDirty = false;
  10891. this.reset();
  10892. }
  10893. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10894. get: function () {
  10895. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10901. get: function () {
  10902. return this._stencilFunc;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilFunc === value) {
  10906. return;
  10907. }
  10908. this._stencilFunc = value;
  10909. this._isStencilFuncDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10915. get: function () {
  10916. return this._stencilFuncRef;
  10917. },
  10918. set: function (value) {
  10919. if (this._stencilFuncRef === value) {
  10920. return;
  10921. }
  10922. this._stencilFuncRef = value;
  10923. this._isStencilFuncDirty = true;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10929. get: function () {
  10930. return this._stencilFuncMask;
  10931. },
  10932. set: function (value) {
  10933. if (this._stencilFuncMask === value) {
  10934. return;
  10935. }
  10936. this._stencilFuncMask = value;
  10937. this._isStencilFuncDirty = true;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10943. get: function () {
  10944. return this._stencilOpStencilFail;
  10945. },
  10946. set: function (value) {
  10947. if (this._stencilOpStencilFail === value) {
  10948. return;
  10949. }
  10950. this._stencilOpStencilFail = value;
  10951. this._isStencilOpDirty = true;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10957. get: function () {
  10958. return this._stencilOpDepthFail;
  10959. },
  10960. set: function (value) {
  10961. if (this._stencilOpDepthFail === value) {
  10962. return;
  10963. }
  10964. this._stencilOpDepthFail = value;
  10965. this._isStencilOpDirty = true;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10971. get: function () {
  10972. return this._stencilOpStencilDepthPass;
  10973. },
  10974. set: function (value) {
  10975. if (this._stencilOpStencilDepthPass === value) {
  10976. return;
  10977. }
  10978. this._stencilOpStencilDepthPass = value;
  10979. this._isStencilOpDirty = true;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10985. get: function () {
  10986. return this._stencilMask;
  10987. },
  10988. set: function (value) {
  10989. if (this._stencilMask === value) {
  10990. return;
  10991. }
  10992. this._stencilMask = value;
  10993. this._isStencilMaskDirty = true;
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10999. get: function () {
  11000. return this._stencilTest;
  11001. },
  11002. set: function (value) {
  11003. if (this._stencilTest === value) {
  11004. return;
  11005. }
  11006. this._stencilTest = value;
  11007. this._isStencilTestDirty = true;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. _StencilState.prototype.reset = function () {
  11013. this._stencilTest = false;
  11014. this._stencilMask = 0xFF;
  11015. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11016. this._stencilFuncRef = 1;
  11017. this._stencilFuncMask = 0xFF;
  11018. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11019. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11020. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11021. this._isStencilTestDirty = true;
  11022. this._isStencilMaskDirty = true;
  11023. this._isStencilFuncDirty = true;
  11024. this._isStencilOpDirty = true;
  11025. };
  11026. _StencilState.prototype.apply = function (gl) {
  11027. if (!this.isDirty) {
  11028. return;
  11029. }
  11030. // Stencil test
  11031. if (this._isStencilTestDirty) {
  11032. if (this.stencilTest) {
  11033. gl.enable(gl.STENCIL_TEST);
  11034. }
  11035. else {
  11036. gl.disable(gl.STENCIL_TEST);
  11037. }
  11038. this._isStencilTestDirty = false;
  11039. }
  11040. // Stencil mask
  11041. if (this._isStencilMaskDirty) {
  11042. gl.stencilMask(this.stencilMask);
  11043. this._isStencilMaskDirty = false;
  11044. }
  11045. // Stencil func
  11046. if (this._isStencilFuncDirty) {
  11047. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11048. this._isStencilFuncDirty = false;
  11049. }
  11050. // Stencil op
  11051. if (this._isStencilOpDirty) {
  11052. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11053. this._isStencilOpDirty = false;
  11054. }
  11055. };
  11056. return _StencilState;
  11057. }());
  11058. BABYLON._StencilState = _StencilState;
  11059. })(BABYLON || (BABYLON = {}));
  11060. //# sourceMappingURL=babylon.stencilState.js.map
  11061. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11062. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11063. s = arguments[i];
  11064. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11065. t[p] = s[p];
  11066. }
  11067. return t;
  11068. };
  11069. var BABYLON;
  11070. (function (BABYLON) {
  11071. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11072. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11073. };
  11074. var compileRawShader = function (gl, source, type) {
  11075. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11076. gl.shaderSource(shader, source);
  11077. gl.compileShader(shader);
  11078. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11079. var log = gl.getShaderInfoLog(shader);
  11080. if (log) {
  11081. throw new Error(log);
  11082. }
  11083. }
  11084. if (!shader) {
  11085. throw new Error("Something went wrong while compile the shader.");
  11086. }
  11087. return shader;
  11088. };
  11089. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11090. var magFilter = gl.NEAREST;
  11091. var minFilter = gl.NEAREST;
  11092. switch (samplingMode) {
  11093. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11094. magFilter = gl.LINEAR;
  11095. if (generateMipMaps) {
  11096. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11097. }
  11098. else {
  11099. minFilter = gl.LINEAR;
  11100. }
  11101. break;
  11102. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11103. magFilter = gl.LINEAR;
  11104. if (generateMipMaps) {
  11105. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11106. }
  11107. else {
  11108. minFilter = gl.LINEAR;
  11109. }
  11110. break;
  11111. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11112. magFilter = gl.NEAREST;
  11113. if (generateMipMaps) {
  11114. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11115. }
  11116. else {
  11117. minFilter = gl.NEAREST;
  11118. }
  11119. break;
  11120. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11121. magFilter = gl.NEAREST;
  11122. if (generateMipMaps) {
  11123. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11124. }
  11125. else {
  11126. minFilter = gl.NEAREST;
  11127. }
  11128. break;
  11129. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11130. magFilter = gl.NEAREST;
  11131. if (generateMipMaps) {
  11132. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11133. }
  11134. else {
  11135. minFilter = gl.LINEAR;
  11136. }
  11137. break;
  11138. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11139. magFilter = gl.NEAREST;
  11140. if (generateMipMaps) {
  11141. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11142. }
  11143. else {
  11144. minFilter = gl.LINEAR;
  11145. }
  11146. break;
  11147. case BABYLON.Texture.NEAREST_LINEAR:
  11148. magFilter = gl.NEAREST;
  11149. minFilter = gl.LINEAR;
  11150. break;
  11151. case BABYLON.Texture.NEAREST_NEAREST:
  11152. magFilter = gl.NEAREST;
  11153. minFilter = gl.NEAREST;
  11154. break;
  11155. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11156. magFilter = gl.LINEAR;
  11157. if (generateMipMaps) {
  11158. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11159. }
  11160. else {
  11161. minFilter = gl.NEAREST;
  11162. }
  11163. break;
  11164. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11165. magFilter = gl.LINEAR;
  11166. if (generateMipMaps) {
  11167. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11168. }
  11169. else {
  11170. minFilter = gl.NEAREST;
  11171. }
  11172. break;
  11173. case BABYLON.Texture.LINEAR_LINEAR:
  11174. magFilter = gl.LINEAR;
  11175. minFilter = gl.LINEAR;
  11176. break;
  11177. case BABYLON.Texture.LINEAR_NEAREST:
  11178. magFilter = gl.LINEAR;
  11179. minFilter = gl.NEAREST;
  11180. break;
  11181. }
  11182. return {
  11183. min: minFilter,
  11184. mag: magFilter
  11185. };
  11186. };
  11187. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11188. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11189. var img;
  11190. var onload = function () {
  11191. loadedImages[index] = img;
  11192. loadedImages._internalCount++;
  11193. if (scene) {
  11194. scene._removePendingData(img);
  11195. }
  11196. if (loadedImages._internalCount === 6) {
  11197. onfinish(loadedImages);
  11198. }
  11199. };
  11200. var onerror = function (message, exception) {
  11201. if (scene) {
  11202. scene._removePendingData(img);
  11203. }
  11204. if (onErrorCallBack) {
  11205. onErrorCallBack(message, exception);
  11206. }
  11207. };
  11208. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11209. if (scene) {
  11210. scene._addPendingData(img);
  11211. }
  11212. };
  11213. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11214. if (onError === void 0) { onError = null; }
  11215. var loadedImages = [];
  11216. loadedImages._internalCount = 0;
  11217. for (var index = 0; index < 6; index++) {
  11218. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11219. }
  11220. };
  11221. var BufferPointer = /** @class */ (function () {
  11222. function BufferPointer() {
  11223. }
  11224. return BufferPointer;
  11225. }());
  11226. /**
  11227. * Interface for attribute information associated with buffer instanciation
  11228. */
  11229. var InstancingAttributeInfo = /** @class */ (function () {
  11230. function InstancingAttributeInfo() {
  11231. }
  11232. return InstancingAttributeInfo;
  11233. }());
  11234. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11235. /**
  11236. * Define options used to create a render target texture
  11237. */
  11238. var RenderTargetCreationOptions = /** @class */ (function () {
  11239. function RenderTargetCreationOptions() {
  11240. }
  11241. return RenderTargetCreationOptions;
  11242. }());
  11243. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11244. /**
  11245. * Define options used to create a depth texture
  11246. */
  11247. var DepthTextureCreationOptions = /** @class */ (function () {
  11248. function DepthTextureCreationOptions() {
  11249. }
  11250. return DepthTextureCreationOptions;
  11251. }());
  11252. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11253. /**
  11254. * Class used to describe the capabilities of the engine relatively to the current browser
  11255. */
  11256. var EngineCapabilities = /** @class */ (function () {
  11257. function EngineCapabilities() {
  11258. }
  11259. return EngineCapabilities;
  11260. }());
  11261. BABYLON.EngineCapabilities = EngineCapabilities;
  11262. /**
  11263. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11264. */
  11265. var Engine = /** @class */ (function () {
  11266. /**
  11267. * Creates a new engine
  11268. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11269. * @param antialias defines enable antialiasing (default: false)
  11270. * @param options defines further options to be sent to the getContext() function
  11271. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11272. */
  11273. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11274. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11275. var _this = this;
  11276. // Public members
  11277. /**
  11278. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11279. */
  11280. this.forcePOTTextures = false;
  11281. /**
  11282. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11283. */
  11284. this.isFullscreen = false;
  11285. /**
  11286. * Gets a boolean indicating if the pointer is currently locked
  11287. */
  11288. this.isPointerLock = false;
  11289. /**
  11290. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11291. */
  11292. this.cullBackFaces = true;
  11293. /**
  11294. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11295. */
  11296. this.renderEvenInBackground = true;
  11297. /**
  11298. * Gets or sets a boolean indicating that cache can be kept between frames
  11299. */
  11300. this.preventCacheWipeBetweenFrames = false;
  11301. /**
  11302. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11303. **/
  11304. this.enableOfflineSupport = false;
  11305. /**
  11306. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11307. **/
  11308. this.disableManifestCheck = false;
  11309. /**
  11310. * Gets the list of created scenes
  11311. */
  11312. this.scenes = new Array();
  11313. /**
  11314. * Gets the list of created postprocesses
  11315. */
  11316. this.postProcesses = new Array();
  11317. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11318. this.validateShaderPrograms = false;
  11319. // Observables
  11320. /**
  11321. * Observable event triggered each time the rendering canvas is resized
  11322. */
  11323. this.onResizeObservable = new BABYLON.Observable();
  11324. /**
  11325. * Observable event triggered each time the canvas loses focus
  11326. */
  11327. this.onCanvasBlurObservable = new BABYLON.Observable();
  11328. /**
  11329. * Observable event triggered each time the canvas gains focus
  11330. */
  11331. this.onCanvasFocusObservable = new BABYLON.Observable();
  11332. /**
  11333. * Observable event triggered each time the canvas receives pointerout event
  11334. */
  11335. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11336. /**
  11337. * Observable event triggered before each texture is initialized
  11338. */
  11339. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11340. //WebVR
  11341. this._vrDisplay = undefined;
  11342. this._vrSupported = false;
  11343. this._vrExclusivePointerMode = false;
  11344. // Uniform buffers list
  11345. /**
  11346. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11347. */
  11348. this.disableUniformBuffers = false;
  11349. /** @hidden */
  11350. this._uniformBuffers = new Array();
  11351. // Observables
  11352. /**
  11353. * Observable raised when the engine begins a new frame
  11354. */
  11355. this.onBeginFrameObservable = new BABYLON.Observable();
  11356. /**
  11357. * Observable raised when the engine ends the current frame
  11358. */
  11359. this.onEndFrameObservable = new BABYLON.Observable();
  11360. /**
  11361. * Observable raised when the engine is about to compile a shader
  11362. */
  11363. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11364. /**
  11365. * Observable raised when the engine has jsut compiled a shader
  11366. */
  11367. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11368. this._windowIsBackground = false;
  11369. this._webGLVersion = 1.0;
  11370. /** @hidden */
  11371. this._badOS = false;
  11372. /** @hidden */
  11373. this._badDesktopOS = false;
  11374. /**
  11375. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11376. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11377. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11378. */
  11379. this.disableTextureBindingOptimization = false;
  11380. /**
  11381. * Observable signaled when VR display mode changes
  11382. */
  11383. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11384. /**
  11385. * Observable signaled when VR request present is complete
  11386. */
  11387. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11388. /**
  11389. * Observable signaled when VR request present starts
  11390. */
  11391. this.onVRRequestPresentStart = new BABYLON.Observable();
  11392. this._colorWrite = true;
  11393. /** @hidden */
  11394. this._drawCalls = new BABYLON.PerfCounter();
  11395. /** @hidden */
  11396. this._textureCollisions = new BABYLON.PerfCounter();
  11397. this._renderingQueueLaunched = false;
  11398. this._activeRenderLoops = new Array();
  11399. // Deterministic lockstepMaxSteps
  11400. this._deterministicLockstep = false;
  11401. this._lockstepMaxSteps = 4;
  11402. // Lost context
  11403. /**
  11404. * Observable signaled when a context lost event is raised
  11405. */
  11406. this.onContextLostObservable = new BABYLON.Observable();
  11407. /**
  11408. * Observable signaled when a context restored event is raised
  11409. */
  11410. this.onContextRestoredObservable = new BABYLON.Observable();
  11411. this._contextWasLost = false;
  11412. this._doNotHandleContextLost = false;
  11413. // FPS
  11414. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11415. this._fps = 60;
  11416. this._deltaTime = 0;
  11417. /**
  11418. * Turn this value on if you want to pause FPS computation when in background
  11419. */
  11420. this.disablePerformanceMonitorInBackground = false;
  11421. // States
  11422. /** @hidden */
  11423. this._depthCullingState = new BABYLON._DepthCullingState();
  11424. /** @hidden */
  11425. this._stencilState = new BABYLON._StencilState();
  11426. /** @hidden */
  11427. this._alphaState = new BABYLON._AlphaState();
  11428. /** @hidden */
  11429. this._alphaMode = Engine.ALPHA_DISABLE;
  11430. // Cache
  11431. this._internalTexturesCache = new Array();
  11432. /** @hidden */
  11433. this._activeChannel = 0;
  11434. this._currentTextureChannel = -1;
  11435. /** @hidden */
  11436. this._boundTexturesCache = {};
  11437. this._compiledEffects = {};
  11438. this._vertexAttribArraysEnabled = [];
  11439. this._uintIndicesCurrentlySet = false;
  11440. this._currentBoundBuffer = new Array();
  11441. /** @hidden */
  11442. this._currentFramebuffer = null;
  11443. this._currentBufferPointers = new Array();
  11444. this._currentInstanceLocations = new Array();
  11445. this._currentInstanceBuffers = new Array();
  11446. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11447. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11448. this._vaoRecordInProgress = false;
  11449. this._mustWipeVertexAttributes = false;
  11450. this._nextFreeTextureSlots = new Array();
  11451. this._maxSimultaneousTextures = 0;
  11452. this._activeRequests = new Array();
  11453. // Hardware supported Compressed Textures
  11454. this._texturesSupported = new Array();
  11455. /**
  11456. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11457. */
  11458. this.premultipliedAlpha = true;
  11459. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11460. this._onVRFullScreenTriggered = function () {
  11461. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11462. //get the old size before we change
  11463. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11464. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11465. //get the width and height, change the render size
  11466. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11467. _this.setHardwareScalingLevel(1);
  11468. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11469. }
  11470. else {
  11471. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11472. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11473. }
  11474. };
  11475. this._unpackFlipYCached = null;
  11476. this._boundUniforms = {};
  11477. // Register promises
  11478. BABYLON.PromisePolyfill.Apply();
  11479. var canvas = null;
  11480. Engine.Instances.push(this);
  11481. if (!canvasOrContext) {
  11482. return;
  11483. }
  11484. options = options || {};
  11485. if (canvasOrContext.getContext) {
  11486. canvas = canvasOrContext;
  11487. this._renderingCanvas = canvas;
  11488. if (antialias != null) {
  11489. options.antialias = antialias;
  11490. }
  11491. if (options.deterministicLockstep === undefined) {
  11492. options.deterministicLockstep = false;
  11493. }
  11494. if (options.lockstepMaxSteps === undefined) {
  11495. options.lockstepMaxSteps = 4;
  11496. }
  11497. if (options.preserveDrawingBuffer === undefined) {
  11498. options.preserveDrawingBuffer = false;
  11499. }
  11500. if (options.audioEngine === undefined) {
  11501. options.audioEngine = true;
  11502. }
  11503. if (options.stencil === undefined) {
  11504. options.stencil = true;
  11505. }
  11506. if (options.premultipliedAlpha === false) {
  11507. this.premultipliedAlpha = false;
  11508. }
  11509. this._deterministicLockstep = options.deterministicLockstep;
  11510. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11511. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11512. // Exceptions
  11513. if (navigator && navigator.userAgent) {
  11514. var ua = navigator.userAgent;
  11515. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11516. var exception = _a[_i];
  11517. var key = exception.key;
  11518. var targets = exception.targets;
  11519. if (ua.indexOf(key) > -1) {
  11520. if (exception.capture && exception.captureConstraint) {
  11521. var capture = exception.capture;
  11522. var constraint = exception.captureConstraint;
  11523. var regex = new RegExp(capture);
  11524. var matches = regex.exec(ua);
  11525. if (matches && matches.length > 0) {
  11526. var capturedValue = parseInt(matches[matches.length - 1]);
  11527. if (capturedValue >= constraint) {
  11528. continue;
  11529. }
  11530. }
  11531. }
  11532. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11533. var target = targets_1[_b];
  11534. switch (target) {
  11535. case "uniformBuffer":
  11536. this.disableUniformBuffers = true;
  11537. break;
  11538. case "textureBindingOptimization":
  11539. this.disableTextureBindingOptimization = true;
  11540. break;
  11541. }
  11542. }
  11543. }
  11544. }
  11545. }
  11546. // GL
  11547. if (!options.disableWebGL2Support) {
  11548. try {
  11549. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11550. if (this._gl) {
  11551. this._webGLVersion = 2.0;
  11552. }
  11553. }
  11554. catch (e) {
  11555. // Do nothing
  11556. }
  11557. }
  11558. if (!this._gl) {
  11559. if (!canvas) {
  11560. throw new Error("The provided canvas is null or undefined.");
  11561. }
  11562. try {
  11563. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11564. }
  11565. catch (e) {
  11566. throw new Error("WebGL not supported");
  11567. }
  11568. }
  11569. if (!this._gl) {
  11570. throw new Error("WebGL not supported");
  11571. }
  11572. this._onCanvasFocus = function () {
  11573. _this.onCanvasFocusObservable.notifyObservers(_this);
  11574. };
  11575. this._onCanvasBlur = function () {
  11576. _this.onCanvasBlurObservable.notifyObservers(_this);
  11577. };
  11578. canvas.addEventListener("focus", this._onCanvasFocus);
  11579. canvas.addEventListener("blur", this._onCanvasBlur);
  11580. this._onBlur = function () {
  11581. if (_this.disablePerformanceMonitorInBackground) {
  11582. _this._performanceMonitor.disable();
  11583. }
  11584. _this._windowIsBackground = true;
  11585. };
  11586. this._onFocus = function () {
  11587. if (_this.disablePerformanceMonitorInBackground) {
  11588. _this._performanceMonitor.enable();
  11589. }
  11590. _this._windowIsBackground = false;
  11591. };
  11592. this._onCanvasPointerOut = function (ev) {
  11593. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11594. };
  11595. window.addEventListener("blur", this._onBlur);
  11596. window.addEventListener("focus", this._onFocus);
  11597. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11598. // Context lost
  11599. if (!this._doNotHandleContextLost) {
  11600. this._onContextLost = function (evt) {
  11601. evt.preventDefault();
  11602. _this._contextWasLost = true;
  11603. BABYLON.Tools.Warn("WebGL context lost.");
  11604. _this.onContextLostObservable.notifyObservers(_this);
  11605. };
  11606. this._onContextRestored = function (evt) {
  11607. // Adding a timeout to avoid race condition at browser level
  11608. setTimeout(function () {
  11609. // Rebuild gl context
  11610. _this._initGLContext();
  11611. // Rebuild effects
  11612. _this._rebuildEffects();
  11613. // Rebuild textures
  11614. _this._rebuildInternalTextures();
  11615. // Rebuild buffers
  11616. _this._rebuildBuffers();
  11617. // Cache
  11618. _this.wipeCaches(true);
  11619. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11620. _this.onContextRestoredObservable.notifyObservers(_this);
  11621. _this._contextWasLost = false;
  11622. }, 0);
  11623. };
  11624. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11625. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11626. }
  11627. }
  11628. else {
  11629. this._gl = canvasOrContext;
  11630. this._renderingCanvas = this._gl.canvas;
  11631. if (this._gl.renderbufferStorageMultisample) {
  11632. this._webGLVersion = 2.0;
  11633. }
  11634. options.stencil = this._gl.getContextAttributes().stencil;
  11635. }
  11636. // Viewport
  11637. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11638. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11639. this.resize();
  11640. this._isStencilEnable = options.stencil ? true : false;
  11641. this._initGLContext();
  11642. if (canvas) {
  11643. // Fullscreen
  11644. this._onFullscreenChange = function () {
  11645. if (document.fullscreen !== undefined) {
  11646. _this.isFullscreen = document.fullscreen;
  11647. }
  11648. else if (document.mozFullScreen !== undefined) {
  11649. _this.isFullscreen = document.mozFullScreen;
  11650. }
  11651. else if (document.webkitIsFullScreen !== undefined) {
  11652. _this.isFullscreen = document.webkitIsFullScreen;
  11653. }
  11654. else if (document.msIsFullScreen !== undefined) {
  11655. _this.isFullscreen = document.msIsFullScreen;
  11656. }
  11657. // Pointer lock
  11658. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11659. canvas.requestPointerLock = canvas.requestPointerLock ||
  11660. canvas.msRequestPointerLock ||
  11661. canvas.mozRequestPointerLock ||
  11662. canvas.webkitRequestPointerLock;
  11663. if (canvas.requestPointerLock) {
  11664. canvas.requestPointerLock();
  11665. }
  11666. }
  11667. };
  11668. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11669. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11670. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11671. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11672. // Pointer lock
  11673. this._onPointerLockChange = function () {
  11674. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11675. document.webkitPointerLockElement === canvas ||
  11676. document.msPointerLockElement === canvas ||
  11677. document.pointerLockElement === canvas);
  11678. };
  11679. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11680. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11681. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11682. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11683. this._onVRDisplayPointerRestricted = function () {
  11684. if (canvas) {
  11685. canvas.requestPointerLock();
  11686. }
  11687. };
  11688. this._onVRDisplayPointerUnrestricted = function () {
  11689. document.exitPointerLock();
  11690. };
  11691. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11692. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11693. }
  11694. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11695. Engine.audioEngine = new BABYLON.AudioEngine();
  11696. }
  11697. // Prepare buffer pointers
  11698. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11699. this._currentBufferPointers[i] = new BufferPointer();
  11700. }
  11701. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11702. // Load WebVR Devices
  11703. if (options.autoEnableWebVR) {
  11704. this.initWebVR();
  11705. }
  11706. // Detect if we are running on a faulty buggy OS.
  11707. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11708. // Detect if we are running on a faulty buggy desktop OS.
  11709. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11710. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11711. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11712. }
  11713. Object.defineProperty(Engine, "LastCreatedEngine", {
  11714. /**
  11715. * Gets the latest created engine
  11716. */
  11717. get: function () {
  11718. if (Engine.Instances.length === 0) {
  11719. return null;
  11720. }
  11721. return Engine.Instances[Engine.Instances.length - 1];
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Engine, "LastCreatedScene", {
  11727. /**
  11728. * Gets the latest created scene
  11729. */
  11730. get: function () {
  11731. var lastCreatedEngine = Engine.LastCreatedEngine;
  11732. if (!lastCreatedEngine) {
  11733. return null;
  11734. }
  11735. if (lastCreatedEngine.scenes.length === 0) {
  11736. return null;
  11737. }
  11738. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. /**
  11744. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11745. * @param flag defines which part of the materials must be marked as dirty
  11746. * @param predicate defines a predicate used to filter which materials should be affected
  11747. */
  11748. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11749. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11750. var engine = Engine.Instances[engineIndex];
  11751. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11752. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11753. }
  11754. }
  11755. };
  11756. Object.defineProperty(Engine, "NEVER", {
  11757. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11758. get: function () {
  11759. return Engine._NEVER;
  11760. },
  11761. enumerable: true,
  11762. configurable: true
  11763. });
  11764. Object.defineProperty(Engine, "ALWAYS", {
  11765. /** 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 */
  11766. get: function () {
  11767. return Engine._ALWAYS;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. Object.defineProperty(Engine, "LESS", {
  11773. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11774. get: function () {
  11775. return Engine._LESS;
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine, "EQUAL", {
  11781. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11782. get: function () {
  11783. return Engine._EQUAL;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "LEQUAL", {
  11789. /** 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 */
  11790. get: function () {
  11791. return Engine._LEQUAL;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "GREATER", {
  11797. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11798. get: function () {
  11799. return Engine._GREATER;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "GEQUAL", {
  11805. /** 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 */
  11806. get: function () {
  11807. return Engine._GEQUAL;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "NOTEQUAL", {
  11813. /** 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 */
  11814. get: function () {
  11815. return Engine._NOTEQUAL;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "KEEP", {
  11821. /** Passed to stencilOperation to specify that stencil value must be kept */
  11822. get: function () {
  11823. return Engine._KEEP;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "REPLACE", {
  11829. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11830. get: function () {
  11831. return Engine._REPLACE;
  11832. },
  11833. enumerable: true,
  11834. configurable: true
  11835. });
  11836. Object.defineProperty(Engine, "INCR", {
  11837. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11838. get: function () {
  11839. return Engine._INCR;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine, "DECR", {
  11845. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11846. get: function () {
  11847. return Engine._DECR;
  11848. },
  11849. enumerable: true,
  11850. configurable: true
  11851. });
  11852. Object.defineProperty(Engine, "INVERT", {
  11853. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11854. get: function () {
  11855. return Engine._INVERT;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "INCR_WRAP", {
  11861. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11862. get: function () {
  11863. return Engine._INCR_WRAP;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "DECR_WRAP", {
  11869. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11870. get: function () {
  11871. return Engine._DECR_WRAP;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11877. // Alpha
  11878. /** Defines that alpha blending is disabled */
  11879. get: function () {
  11880. return Engine._ALPHA_DISABLE;
  11881. },
  11882. enumerable: true,
  11883. configurable: true
  11884. });
  11885. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11886. /** Defines that alpha blending to SRC + DEST */
  11887. get: function () {
  11888. return Engine._ALPHA_ONEONE;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Engine, "ALPHA_ADD", {
  11894. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11895. get: function () {
  11896. return Engine._ALPHA_ADD;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11902. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11903. get: function () {
  11904. return Engine._ALPHA_COMBINE;
  11905. },
  11906. enumerable: true,
  11907. configurable: true
  11908. });
  11909. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11910. /** Defines that alpha blending to DEST - SRC * DEST */
  11911. get: function () {
  11912. return Engine._ALPHA_SUBTRACT;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11918. /** Defines that alpha blending to SRC * DEST */
  11919. get: function () {
  11920. return Engine._ALPHA_MULTIPLY;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11926. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11927. get: function () {
  11928. return Engine._ALPHA_MAXIMIZED;
  11929. },
  11930. enumerable: true,
  11931. configurable: true
  11932. });
  11933. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11934. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11935. get: function () {
  11936. return Engine._ALPHA_PREMULTIPLIED;
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11942. /**
  11943. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11944. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11945. */
  11946. get: function () {
  11947. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11953. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11954. get: function () {
  11955. return Engine._ALPHA_INTERPOLATE;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11961. /**
  11962. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11963. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11964. */
  11965. get: function () {
  11966. return Engine._ALPHA_SCREENMODE;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11972. // Delays
  11973. /** Defines that the ressource is not delayed*/
  11974. get: function () {
  11975. return Engine._DELAYLOADSTATE_NONE;
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11981. /** Defines that the ressource was successfully delay loaded */
  11982. get: function () {
  11983. return Engine._DELAYLOADSTATE_LOADED;
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11989. /** Defines that the ressource is currently delay loading */
  11990. get: function () {
  11991. return Engine._DELAYLOADSTATE_LOADING;
  11992. },
  11993. enumerable: true,
  11994. configurable: true
  11995. });
  11996. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11997. /** Defines that the ressource is delayed and has not started loading */
  11998. get: function () {
  11999. return Engine._DELAYLOADSTATE_NOTLOADED;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12005. /** ALPHA */
  12006. get: function () {
  12007. return Engine._TEXTUREFORMAT_ALPHA;
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12013. /** LUMINANCE */
  12014. get: function () {
  12015. return Engine._TEXTUREFORMAT_LUMINANCE;
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12021. /**
  12022. * R
  12023. */
  12024. get: function () {
  12025. return Engine._TEXTUREFORMAT_R;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12031. /**
  12032. * RG
  12033. */
  12034. get: function () {
  12035. return Engine._TEXTUREFORMAT_RG;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12041. /** LUMINANCE_ALPHA */
  12042. get: function () {
  12043. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12049. /** RGB */
  12050. get: function () {
  12051. return Engine._TEXTUREFORMAT_RGB;
  12052. },
  12053. enumerable: true,
  12054. configurable: true
  12055. });
  12056. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12057. /** RGBA */
  12058. get: function () {
  12059. return Engine._TEXTUREFORMAT_RGBA;
  12060. },
  12061. enumerable: true,
  12062. configurable: true
  12063. });
  12064. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12065. /** UNSIGNED_INT */
  12066. get: function () {
  12067. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12073. /** FLOAT */
  12074. get: function () {
  12075. return Engine._TEXTURETYPE_FLOAT;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12081. /** HALF_FLOAT */
  12082. get: function () {
  12083. return Engine._TEXTURETYPE_HALF_FLOAT;
  12084. },
  12085. enumerable: true,
  12086. configurable: true
  12087. });
  12088. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12089. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12090. get: function () {
  12091. return Engine._SCALEMODE_FLOOR;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12097. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12098. get: function () {
  12099. return Engine._SCALEMODE_NEAREST;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12105. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12106. get: function () {
  12107. return Engine._SCALEMODE_CEILING;
  12108. },
  12109. enumerable: true,
  12110. configurable: true
  12111. });
  12112. Object.defineProperty(Engine, "Version", {
  12113. /**
  12114. * Returns the current version of the framework
  12115. */
  12116. get: function () {
  12117. return "3.3.0-alpha.9";
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12123. /**
  12124. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12125. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12126. */
  12127. get: function () {
  12128. return this._vrExclusivePointerMode;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12134. /**
  12135. * Gets a boolean indicating that the engine supports uniform buffers
  12136. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12137. */
  12138. get: function () {
  12139. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12145. /**
  12146. * Gets a boolean indicating that only power of 2 textures are supported
  12147. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12148. */
  12149. get: function () {
  12150. return this._webGLVersion < 2 || this.forcePOTTextures;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12156. /**
  12157. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12158. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12159. */
  12160. get: function () {
  12161. return this._doNotHandleContextLost;
  12162. },
  12163. set: function (value) {
  12164. this._doNotHandleContextLost = value;
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12170. /**
  12171. * Gets the performance monitor attached to this engine
  12172. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12173. */
  12174. get: function () {
  12175. return this._performanceMonitor;
  12176. },
  12177. enumerable: true,
  12178. configurable: true
  12179. });
  12180. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12181. /**
  12182. * Gets the list of texture formats supported
  12183. */
  12184. get: function () {
  12185. return this._texturesSupported;
  12186. },
  12187. enumerable: true,
  12188. configurable: true
  12189. });
  12190. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12191. /**
  12192. * Gets the list of texture formats in use
  12193. */
  12194. get: function () {
  12195. return this._textureFormatInUse;
  12196. },
  12197. enumerable: true,
  12198. configurable: true
  12199. });
  12200. Object.defineProperty(Engine.prototype, "currentViewport", {
  12201. /**
  12202. * Gets the current viewport
  12203. */
  12204. get: function () {
  12205. return this._cachedViewport;
  12206. },
  12207. enumerable: true,
  12208. configurable: true
  12209. });
  12210. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12211. /**
  12212. * Gets the default empty texture
  12213. */
  12214. get: function () {
  12215. if (!this._emptyTexture) {
  12216. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12217. }
  12218. return this._emptyTexture;
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12224. /**
  12225. * Gets the default empty 3D texture
  12226. */
  12227. get: function () {
  12228. if (!this._emptyTexture3D) {
  12229. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12230. }
  12231. return this._emptyTexture3D;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12237. /**
  12238. * Gets the default empty cube texture
  12239. */
  12240. get: function () {
  12241. if (!this._emptyCubeTexture) {
  12242. var faceData = new Uint8Array(4);
  12243. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12244. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12245. }
  12246. return this._emptyCubeTexture;
  12247. },
  12248. enumerable: true,
  12249. configurable: true
  12250. });
  12251. Engine.prototype._rebuildInternalTextures = function () {
  12252. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12253. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12254. var internalTexture = currentState_1[_i];
  12255. internalTexture._rebuild();
  12256. }
  12257. };
  12258. Engine.prototype._rebuildEffects = function () {
  12259. for (var key in this._compiledEffects) {
  12260. var effect = this._compiledEffects[key];
  12261. effect._prepareEffect();
  12262. }
  12263. BABYLON.Effect.ResetCache();
  12264. };
  12265. Engine.prototype._rebuildBuffers = function () {
  12266. // Index / Vertex
  12267. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12268. var scene = _a[_i];
  12269. scene.resetCachedMaterial();
  12270. scene._rebuildGeometries();
  12271. scene._rebuildTextures();
  12272. }
  12273. // Uniforms
  12274. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12275. var uniformBuffer = _c[_b];
  12276. uniformBuffer._rebuild();
  12277. }
  12278. };
  12279. Engine.prototype._initGLContext = function () {
  12280. // Caps
  12281. this._caps = new EngineCapabilities();
  12282. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12283. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12284. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12285. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12286. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12287. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12288. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12289. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12290. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12291. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12292. // Infos
  12293. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12294. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12295. if (rendererInfo != null) {
  12296. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12297. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12298. }
  12299. if (!this._glVendor) {
  12300. this._glVendor = "Unknown vendor";
  12301. }
  12302. if (!this._glRenderer) {
  12303. this._glRenderer = "Unknown renderer";
  12304. }
  12305. // Constants
  12306. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12307. if (this._gl.RGBA16F !== 0x881A) {
  12308. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12309. }
  12310. if (this._gl.RGBA32F !== 0x8814) {
  12311. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12312. }
  12313. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12314. this._gl.DEPTH24_STENCIL8 = 35056;
  12315. }
  12316. // Extensions
  12317. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12318. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12319. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12320. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12321. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12322. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12323. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12324. 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');
  12325. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12326. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12327. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12328. this._caps.highPrecisionShaderSupported = true;
  12329. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12330. if (this._caps.timerQuery) {
  12331. if (this._webGLVersion === 1) {
  12332. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12333. }
  12334. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12335. }
  12336. // Checks if some of the format renders first to allow the use of webgl inspector.
  12337. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12338. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12339. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12340. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12341. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12342. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12343. if (this._webGLVersion > 1) {
  12344. this._gl.HALF_FLOAT_OES = 0x140B;
  12345. }
  12346. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12347. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12348. // Draw buffers
  12349. if (this._webGLVersion > 1) {
  12350. this._caps.drawBuffersExtension = true;
  12351. }
  12352. else {
  12353. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12354. if (drawBuffersExtension !== null) {
  12355. this._caps.drawBuffersExtension = true;
  12356. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12357. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12358. for (var i = 0; i < 16; i++) {
  12359. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12360. }
  12361. }
  12362. else {
  12363. this._caps.drawBuffersExtension = false;
  12364. }
  12365. }
  12366. // Depth Texture
  12367. if (this._webGLVersion > 1) {
  12368. this._caps.depthTextureExtension = true;
  12369. }
  12370. else {
  12371. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12372. if (depthTextureExtension != null) {
  12373. this._caps.depthTextureExtension = true;
  12374. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12375. }
  12376. }
  12377. // Vertex array object
  12378. if (this._webGLVersion > 1) {
  12379. this._caps.vertexArrayObject = true;
  12380. }
  12381. else {
  12382. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12383. if (vertexArrayObjectExtension != null) {
  12384. this._caps.vertexArrayObject = true;
  12385. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12386. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12387. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12388. }
  12389. else {
  12390. this._caps.vertexArrayObject = false;
  12391. }
  12392. }
  12393. // Instances count
  12394. if (this._webGLVersion > 1) {
  12395. this._caps.instancedArrays = true;
  12396. }
  12397. else {
  12398. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12399. if (instanceExtension != null) {
  12400. this._caps.instancedArrays = true;
  12401. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12402. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12403. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12404. }
  12405. else {
  12406. this._caps.instancedArrays = false;
  12407. }
  12408. }
  12409. // Intelligently add supported compressed formats in order to check for.
  12410. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12411. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12412. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12413. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12414. if (this._caps.astc)
  12415. this.texturesSupported.push('-astc.ktx');
  12416. if (this._caps.s3tc)
  12417. this.texturesSupported.push('-dxt.ktx');
  12418. if (this._caps.pvrtc)
  12419. this.texturesSupported.push('-pvrtc.ktx');
  12420. if (this._caps.etc2)
  12421. this.texturesSupported.push('-etc2.ktx');
  12422. if (this._caps.etc1)
  12423. this.texturesSupported.push('-etc1.ktx');
  12424. if (this._gl.getShaderPrecisionFormat) {
  12425. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12426. if (highp) {
  12427. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12428. }
  12429. }
  12430. // Depth buffer
  12431. this.setDepthBuffer(true);
  12432. this.setDepthFunctionToLessOrEqual();
  12433. this.setDepthWrite(true);
  12434. // Texture maps
  12435. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12436. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12437. this._nextFreeTextureSlots.push(slot);
  12438. }
  12439. };
  12440. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12441. /**
  12442. * Gets version of the current webGL context
  12443. */
  12444. get: function () {
  12445. return this._webGLVersion;
  12446. },
  12447. enumerable: true,
  12448. configurable: true
  12449. });
  12450. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12451. /**
  12452. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12453. */
  12454. get: function () {
  12455. return this._isStencilEnable;
  12456. },
  12457. enumerable: true,
  12458. configurable: true
  12459. });
  12460. Engine.prototype._prepareWorkingCanvas = function () {
  12461. if (this._workingCanvas) {
  12462. return;
  12463. }
  12464. this._workingCanvas = document.createElement("canvas");
  12465. var context = this._workingCanvas.getContext("2d");
  12466. if (context) {
  12467. this._workingContext = context;
  12468. }
  12469. };
  12470. /**
  12471. * Reset the texture cache to empty state
  12472. */
  12473. Engine.prototype.resetTextureCache = function () {
  12474. for (var key in this._boundTexturesCache) {
  12475. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12476. continue;
  12477. }
  12478. var boundTexture = this._boundTexturesCache[key];
  12479. if (boundTexture) {
  12480. this._removeDesignatedSlot(boundTexture);
  12481. }
  12482. this._boundTexturesCache[key] = null;
  12483. }
  12484. if (!this.disableTextureBindingOptimization) {
  12485. this._nextFreeTextureSlots = [];
  12486. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12487. this._nextFreeTextureSlots.push(slot);
  12488. }
  12489. }
  12490. this._currentTextureChannel = -1;
  12491. };
  12492. /**
  12493. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12494. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12495. * @returns true if engine is in deterministic lock step mode
  12496. */
  12497. Engine.prototype.isDeterministicLockStep = function () {
  12498. return this._deterministicLockstep;
  12499. };
  12500. /**
  12501. * Gets the max steps when engine is running in deterministic lock step
  12502. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12503. * @returns the max steps
  12504. */
  12505. Engine.prototype.getLockstepMaxSteps = function () {
  12506. return this._lockstepMaxSteps;
  12507. };
  12508. /**
  12509. * Gets an object containing information about the current webGL context
  12510. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12511. */
  12512. Engine.prototype.getGlInfo = function () {
  12513. return {
  12514. vendor: this._glVendor,
  12515. renderer: this._glRenderer,
  12516. version: this._glVersion
  12517. };
  12518. };
  12519. /**
  12520. * Gets current aspect ratio
  12521. * @param camera defines the camera to use to get the aspect ratio
  12522. * @param useScreen defines if screen size must be used (or the current render target if any)
  12523. * @returns a number defining the aspect ratio
  12524. */
  12525. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12526. if (useScreen === void 0) { useScreen = false; }
  12527. var viewport = camera.viewport;
  12528. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12529. };
  12530. /**
  12531. * Gets current screen aspect ratio
  12532. * @returns a number defining the aspect ratio
  12533. */
  12534. Engine.prototype.getScreenAspectRatio = function () {
  12535. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12536. };
  12537. /**
  12538. * Gets the current render width
  12539. * @param useScreen defines if screen size must be used (or the current render target if any)
  12540. * @returns a number defining the current render width
  12541. */
  12542. Engine.prototype.getRenderWidth = function (useScreen) {
  12543. if (useScreen === void 0) { useScreen = false; }
  12544. if (!useScreen && this._currentRenderTarget) {
  12545. return this._currentRenderTarget.width;
  12546. }
  12547. return this._gl.drawingBufferWidth;
  12548. };
  12549. /**
  12550. * Gets the current render height
  12551. * @param useScreen defines if screen size must be used (or the current render target if any)
  12552. * @returns a number defining the current render height
  12553. */
  12554. Engine.prototype.getRenderHeight = function (useScreen) {
  12555. if (useScreen === void 0) { useScreen = false; }
  12556. if (!useScreen && this._currentRenderTarget) {
  12557. return this._currentRenderTarget.height;
  12558. }
  12559. return this._gl.drawingBufferHeight;
  12560. };
  12561. /**
  12562. * Gets the HTML canvas attached with the current webGL context
  12563. * @returns a HTML canvas
  12564. */
  12565. Engine.prototype.getRenderingCanvas = function () {
  12566. return this._renderingCanvas;
  12567. };
  12568. /**
  12569. * Gets the client rect of the HTML canvas attached with the current webGL context
  12570. * @returns a client rectanglee
  12571. */
  12572. Engine.prototype.getRenderingCanvasClientRect = function () {
  12573. if (!this._renderingCanvas) {
  12574. return null;
  12575. }
  12576. return this._renderingCanvas.getBoundingClientRect();
  12577. };
  12578. /**
  12579. * Defines the hardware scaling level.
  12580. * By default the hardware scaling level is computed from the window device ratio.
  12581. * 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.
  12582. * @param level defines the level to use
  12583. */
  12584. Engine.prototype.setHardwareScalingLevel = function (level) {
  12585. this._hardwareScalingLevel = level;
  12586. this.resize();
  12587. };
  12588. /**
  12589. * Gets the current hardware scaling level.
  12590. * By default the hardware scaling level is computed from the window device ratio.
  12591. * 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.
  12592. * @returns a number indicating the current hardware scaling level
  12593. */
  12594. Engine.prototype.getHardwareScalingLevel = function () {
  12595. return this._hardwareScalingLevel;
  12596. };
  12597. /**
  12598. * Gets the list of loaded textures
  12599. * @returns an array containing all loaded textures
  12600. */
  12601. Engine.prototype.getLoadedTexturesCache = function () {
  12602. return this._internalTexturesCache;
  12603. };
  12604. /**
  12605. * Gets the object containing all engine capabilities
  12606. * @returns the EngineCapabilities object
  12607. */
  12608. Engine.prototype.getCaps = function () {
  12609. return this._caps;
  12610. };
  12611. Object.defineProperty(Engine.prototype, "drawCalls", {
  12612. /** @hidden */
  12613. get: function () {
  12614. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12615. return 0;
  12616. },
  12617. enumerable: true,
  12618. configurable: true
  12619. });
  12620. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12621. /** @hidden */
  12622. get: function () {
  12623. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12624. return null;
  12625. },
  12626. enumerable: true,
  12627. configurable: true
  12628. });
  12629. /**
  12630. * Gets the current depth function
  12631. * @returns a number defining the depth function
  12632. */
  12633. Engine.prototype.getDepthFunction = function () {
  12634. return this._depthCullingState.depthFunc;
  12635. };
  12636. /**
  12637. * Sets the current depth function
  12638. * @param depthFunc defines the function to use
  12639. */
  12640. Engine.prototype.setDepthFunction = function (depthFunc) {
  12641. this._depthCullingState.depthFunc = depthFunc;
  12642. };
  12643. /**
  12644. * Sets the current depth function to GREATER
  12645. */
  12646. Engine.prototype.setDepthFunctionToGreater = function () {
  12647. this._depthCullingState.depthFunc = this._gl.GREATER;
  12648. };
  12649. /**
  12650. * Sets the current depth function to GEQUAL
  12651. */
  12652. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12653. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12654. };
  12655. /**
  12656. * Sets the current depth function to LESS
  12657. */
  12658. Engine.prototype.setDepthFunctionToLess = function () {
  12659. this._depthCullingState.depthFunc = this._gl.LESS;
  12660. };
  12661. /**
  12662. * Sets the current depth function to LEQUAL
  12663. */
  12664. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12665. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12666. };
  12667. /**
  12668. * Gets a boolean indicating if stencil buffer is enabled
  12669. * @returns the current stencil buffer state
  12670. */
  12671. Engine.prototype.getStencilBuffer = function () {
  12672. return this._stencilState.stencilTest;
  12673. };
  12674. /**
  12675. * Enable or disable the stencil buffer
  12676. * @param enable defines if the stencil buffer must be enabled or disabled
  12677. */
  12678. Engine.prototype.setStencilBuffer = function (enable) {
  12679. this._stencilState.stencilTest = enable;
  12680. };
  12681. /**
  12682. * Gets the current stencil mask
  12683. * @returns a number defining the new stencil mask to use
  12684. */
  12685. Engine.prototype.getStencilMask = function () {
  12686. return this._stencilState.stencilMask;
  12687. };
  12688. /**
  12689. * Sets the current stencil mask
  12690. * @param mask defines the new stencil mask to use
  12691. */
  12692. Engine.prototype.setStencilMask = function (mask) {
  12693. this._stencilState.stencilMask = mask;
  12694. };
  12695. /**
  12696. * Gets the current stencil function
  12697. * @returns a number defining the stencil function to use
  12698. */
  12699. Engine.prototype.getStencilFunction = function () {
  12700. return this._stencilState.stencilFunc;
  12701. };
  12702. /**
  12703. * Gets the current stencil reference value
  12704. * @returns a number defining the stencil reference value to use
  12705. */
  12706. Engine.prototype.getStencilFunctionReference = function () {
  12707. return this._stencilState.stencilFuncRef;
  12708. };
  12709. /**
  12710. * Gets the current stencil mask
  12711. * @returns a number defining the stencil mask to use
  12712. */
  12713. Engine.prototype.getStencilFunctionMask = function () {
  12714. return this._stencilState.stencilFuncMask;
  12715. };
  12716. /**
  12717. * Sets the current stencil function
  12718. * @param stencilFunc defines the new stencil function to use
  12719. */
  12720. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12721. this._stencilState.stencilFunc = stencilFunc;
  12722. };
  12723. /**
  12724. * Sets the current stencil reference
  12725. * @param reference defines the new stencil reference to use
  12726. */
  12727. Engine.prototype.setStencilFunctionReference = function (reference) {
  12728. this._stencilState.stencilFuncRef = reference;
  12729. };
  12730. /**
  12731. * Sets the current stencil mask
  12732. * @param mask defines the new stencil mask to use
  12733. */
  12734. Engine.prototype.setStencilFunctionMask = function (mask) {
  12735. this._stencilState.stencilFuncMask = mask;
  12736. };
  12737. /**
  12738. * Gets the current stencil operation when stencil fails
  12739. * @returns a number defining stencil operation to use when stencil fails
  12740. */
  12741. Engine.prototype.getStencilOperationFail = function () {
  12742. return this._stencilState.stencilOpStencilFail;
  12743. };
  12744. /**
  12745. * Gets the current stencil operation when depth fails
  12746. * @returns a number defining stencil operation to use when depth fails
  12747. */
  12748. Engine.prototype.getStencilOperationDepthFail = function () {
  12749. return this._stencilState.stencilOpDepthFail;
  12750. };
  12751. /**
  12752. * Gets the current stencil operation when stencil passes
  12753. * @returns a number defining stencil operation to use when stencil passes
  12754. */
  12755. Engine.prototype.getStencilOperationPass = function () {
  12756. return this._stencilState.stencilOpStencilDepthPass;
  12757. };
  12758. /**
  12759. * Sets the stencil operation to use when stencil fails
  12760. * @param operation defines the stencil operation to use when stencil fails
  12761. */
  12762. Engine.prototype.setStencilOperationFail = function (operation) {
  12763. this._stencilState.stencilOpStencilFail = operation;
  12764. };
  12765. /**
  12766. * Sets the stencil operation to use when depth fails
  12767. * @param operation defines the stencil operation to use when depth fails
  12768. */
  12769. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12770. this._stencilState.stencilOpDepthFail = operation;
  12771. };
  12772. /**
  12773. * Sets the stencil operation to use when stencil passes
  12774. * @param operation defines the stencil operation to use when stencil passes
  12775. */
  12776. Engine.prototype.setStencilOperationPass = function (operation) {
  12777. this._stencilState.stencilOpStencilDepthPass = operation;
  12778. };
  12779. /**
  12780. * Sets a boolean indicating if the dithering state is enabled or disabled
  12781. * @param value defines the dithering state
  12782. */
  12783. Engine.prototype.setDitheringState = function (value) {
  12784. if (value) {
  12785. this._gl.enable(this._gl.DITHER);
  12786. }
  12787. else {
  12788. this._gl.disable(this._gl.DITHER);
  12789. }
  12790. };
  12791. /**
  12792. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12793. * @param value defines the rasterizer state
  12794. */
  12795. Engine.prototype.setRasterizerState = function (value) {
  12796. if (value) {
  12797. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12798. }
  12799. else {
  12800. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12801. }
  12802. };
  12803. /**
  12804. * stop executing a render loop function and remove it from the execution array
  12805. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12806. */
  12807. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12808. if (!renderFunction) {
  12809. this._activeRenderLoops = [];
  12810. return;
  12811. }
  12812. var index = this._activeRenderLoops.indexOf(renderFunction);
  12813. if (index >= 0) {
  12814. this._activeRenderLoops.splice(index, 1);
  12815. }
  12816. };
  12817. /** @hidden */
  12818. Engine.prototype._renderLoop = function () {
  12819. if (!this._contextWasLost) {
  12820. var shouldRender = true;
  12821. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12822. shouldRender = false;
  12823. }
  12824. if (shouldRender) {
  12825. // Start new frame
  12826. this.beginFrame();
  12827. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12828. var renderFunction = this._activeRenderLoops[index];
  12829. renderFunction();
  12830. }
  12831. // Present
  12832. this.endFrame();
  12833. }
  12834. }
  12835. if (this._activeRenderLoops.length > 0) {
  12836. // Register new frame
  12837. var requester = null;
  12838. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12839. requester = this._vrDisplay;
  12840. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12841. }
  12842. else {
  12843. this._renderingQueueLaunched = false;
  12844. }
  12845. };
  12846. /**
  12847. * Register and execute a render loop. The engine can have more than one render function
  12848. * @param renderFunction defines the function to continuously execute
  12849. */
  12850. Engine.prototype.runRenderLoop = function (renderFunction) {
  12851. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12852. return;
  12853. }
  12854. this._activeRenderLoops.push(renderFunction);
  12855. if (!this._renderingQueueLaunched) {
  12856. this._renderingQueueLaunched = true;
  12857. this._bindedRenderFunction = this._renderLoop.bind(this);
  12858. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12859. }
  12860. };
  12861. /**
  12862. * Toggle full screen mode
  12863. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12864. * @param options defines an option object to be sent to the requestFullscreen function
  12865. */
  12866. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12867. if (this.isFullscreen) {
  12868. BABYLON.Tools.ExitFullscreen();
  12869. }
  12870. else {
  12871. this._pointerLockRequested = requestPointerLock;
  12872. if (this._renderingCanvas) {
  12873. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12874. }
  12875. }
  12876. };
  12877. /**
  12878. * Clear the current render buffer or the current render target (if any is set up)
  12879. * @param color defines the color to use
  12880. * @param backBuffer defines if the back buffer must be cleared
  12881. * @param depth defines if the depth buffer must be cleared
  12882. * @param stencil defines if the stencil buffer must be cleared
  12883. */
  12884. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12885. if (stencil === void 0) { stencil = false; }
  12886. this.applyStates();
  12887. var mode = 0;
  12888. if (backBuffer && color) {
  12889. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12890. mode |= this._gl.COLOR_BUFFER_BIT;
  12891. }
  12892. if (depth) {
  12893. this._gl.clearDepth(1.0);
  12894. mode |= this._gl.DEPTH_BUFFER_BIT;
  12895. }
  12896. if (stencil) {
  12897. this._gl.clearStencil(0);
  12898. mode |= this._gl.STENCIL_BUFFER_BIT;
  12899. }
  12900. this._gl.clear(mode);
  12901. };
  12902. /**
  12903. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12904. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12905. * @param y defines the y-coordinate of the corner of the clear rectangle
  12906. * @param width defines the width of the clear rectangle
  12907. * @param height defines the height of the clear rectangle
  12908. * @param clearColor defines the clear color
  12909. */
  12910. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12911. var gl = this._gl;
  12912. // Save state
  12913. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12914. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12915. // Change state
  12916. gl.enable(gl.SCISSOR_TEST);
  12917. gl.scissor(x, y, width, height);
  12918. // Clear
  12919. this.clear(clearColor, true, true, true);
  12920. // Restore state
  12921. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12922. if (curScissor === true) {
  12923. gl.enable(gl.SCISSOR_TEST);
  12924. }
  12925. else {
  12926. gl.disable(gl.SCISSOR_TEST);
  12927. }
  12928. };
  12929. /** @hidden */
  12930. Engine.prototype._viewport = function (x, y, width, height) {
  12931. if (x !== this._viewportCached.x ||
  12932. y !== this._viewportCached.y ||
  12933. width !== this._viewportCached.z ||
  12934. height !== this._viewportCached.w) {
  12935. this._viewportCached.x = x;
  12936. this._viewportCached.y = y;
  12937. this._viewportCached.z = width;
  12938. this._viewportCached.w = height;
  12939. this._gl.viewport(x, y, width, height);
  12940. }
  12941. };
  12942. /**
  12943. * Set the WebGL's viewport
  12944. * @param viewport defines the viewport element to be used
  12945. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12946. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12947. */
  12948. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12949. var width = requiredWidth || this.getRenderWidth();
  12950. var height = requiredHeight || this.getRenderHeight();
  12951. var x = viewport.x || 0;
  12952. var y = viewport.y || 0;
  12953. this._cachedViewport = viewport;
  12954. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12955. };
  12956. /**
  12957. * Directly set the WebGL Viewport
  12958. * @param x defines the x coordinate of the viewport (in screen space)
  12959. * @param y defines the y coordinate of the viewport (in screen space)
  12960. * @param width defines the width of the viewport (in screen space)
  12961. * @param height defines the height of the viewport (in screen space)
  12962. * @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
  12963. */
  12964. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12965. var currentViewport = this._cachedViewport;
  12966. this._cachedViewport = null;
  12967. this._viewport(x, y, width, height);
  12968. return currentViewport;
  12969. };
  12970. /**
  12971. * Begin a new frame
  12972. */
  12973. Engine.prototype.beginFrame = function () {
  12974. this.onBeginFrameObservable.notifyObservers(this);
  12975. this._measureFps();
  12976. };
  12977. /**
  12978. * Enf the current frame
  12979. */
  12980. Engine.prototype.endFrame = function () {
  12981. // Force a flush in case we are using a bad OS.
  12982. if (this._badOS) {
  12983. this.flushFramebuffer();
  12984. }
  12985. // Submit frame to the vr device, if enabled
  12986. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12987. // TODO: We should only submit the frame if we read frameData successfully.
  12988. this._vrDisplay.submitFrame();
  12989. }
  12990. this.onEndFrameObservable.notifyObservers(this);
  12991. };
  12992. /**
  12993. * Resize the view according to the canvas' size
  12994. */
  12995. Engine.prototype.resize = function () {
  12996. // We're not resizing the size of the canvas while in VR mode & presenting
  12997. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12998. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12999. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13000. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13001. }
  13002. };
  13003. /**
  13004. * Force a specific size of the canvas
  13005. * @param width defines the new canvas' width
  13006. * @param height defines the new canvas' height
  13007. */
  13008. Engine.prototype.setSize = function (width, height) {
  13009. if (!this._renderingCanvas) {
  13010. return;
  13011. }
  13012. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13013. return;
  13014. }
  13015. this._renderingCanvas.width = width;
  13016. this._renderingCanvas.height = height;
  13017. for (var index = 0; index < this.scenes.length; index++) {
  13018. var scene = this.scenes[index];
  13019. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13020. var cam = scene.cameras[camIndex];
  13021. cam._currentRenderId = 0;
  13022. }
  13023. }
  13024. if (this.onResizeObservable.hasObservers) {
  13025. this.onResizeObservable.notifyObservers(this);
  13026. }
  13027. };
  13028. // WebVR functions
  13029. /**
  13030. * Gets a boolean indicating if a webVR device was detected
  13031. * @returns true if a webVR device was detected
  13032. */
  13033. Engine.prototype.isVRDevicePresent = function () {
  13034. return !!this._vrDisplay;
  13035. };
  13036. /**
  13037. * Gets the current webVR device
  13038. * @returns the current webVR device (or null)
  13039. */
  13040. Engine.prototype.getVRDevice = function () {
  13041. return this._vrDisplay;
  13042. };
  13043. /**
  13044. * Initializes a webVR display and starts listening to display change events
  13045. * The onVRDisplayChangedObservable will be notified upon these changes
  13046. * @returns The onVRDisplayChangedObservable
  13047. */
  13048. Engine.prototype.initWebVR = function () {
  13049. this.initWebVRAsync();
  13050. return this.onVRDisplayChangedObservable;
  13051. };
  13052. /**
  13053. * Initializes a webVR display and starts listening to display change events
  13054. * The onVRDisplayChangedObservable will be notified upon these changes
  13055. * @returns A promise containing a VRDisplay and if vr is supported
  13056. */
  13057. Engine.prototype.initWebVRAsync = function () {
  13058. var _this = this;
  13059. var notifyObservers = function () {
  13060. var eventArgs = {
  13061. vrDisplay: _this._vrDisplay,
  13062. vrSupported: _this._vrSupported
  13063. };
  13064. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13065. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13066. };
  13067. if (!this._onVrDisplayConnect) {
  13068. this._onVrDisplayConnect = function (event) {
  13069. _this._vrDisplay = event.display;
  13070. notifyObservers();
  13071. };
  13072. this._onVrDisplayDisconnect = function () {
  13073. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13074. _this._vrDisplay = undefined;
  13075. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13076. notifyObservers();
  13077. };
  13078. this._onVrDisplayPresentChange = function () {
  13079. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13080. };
  13081. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13082. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13083. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13084. }
  13085. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13086. this._webVRInitPromise.then(notifyObservers);
  13087. return this._webVRInitPromise;
  13088. };
  13089. /**
  13090. * Call this function to switch to webVR mode
  13091. * Will do nothing if webVR is not supported or if there is no webVR device
  13092. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13093. */
  13094. Engine.prototype.enableVR = function () {
  13095. var _this = this;
  13096. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13097. var onResolved = function () {
  13098. _this.onVRRequestPresentComplete.notifyObservers(true);
  13099. _this._onVRFullScreenTriggered();
  13100. };
  13101. var onRejected = function () {
  13102. _this.onVRRequestPresentComplete.notifyObservers(false);
  13103. };
  13104. this.onVRRequestPresentStart.notifyObservers(this);
  13105. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13106. }
  13107. };
  13108. /**
  13109. * Call this function to leave webVR mode
  13110. * Will do nothing if webVR is not supported or if there is no webVR device
  13111. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13112. */
  13113. Engine.prototype.disableVR = function () {
  13114. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13115. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13116. }
  13117. };
  13118. Engine.prototype._getVRDisplaysAsync = function () {
  13119. var _this = this;
  13120. return new Promise(function (res, rej) {
  13121. if (navigator.getVRDisplays) {
  13122. navigator.getVRDisplays().then(function (devices) {
  13123. _this._vrSupported = true;
  13124. // note that devices may actually be an empty array. This is fine;
  13125. // we expect this._vrDisplay to be undefined in this case.
  13126. _this._vrDisplay = devices[0];
  13127. res({
  13128. vrDisplay: _this._vrDisplay,
  13129. vrSupported: _this._vrSupported
  13130. });
  13131. });
  13132. }
  13133. else {
  13134. _this._vrDisplay = undefined;
  13135. _this._vrSupported = false;
  13136. res({
  13137. vrDisplay: _this._vrDisplay,
  13138. vrSupported: _this._vrSupported
  13139. });
  13140. }
  13141. });
  13142. };
  13143. /**
  13144. * Binds the frame buffer to the specified texture.
  13145. * @param texture The texture to render to or null for the default canvas
  13146. * @param faceIndex The face of the texture to render to in case of cube texture
  13147. * @param requiredWidth The width of the target to render to
  13148. * @param requiredHeight The height of the target to render to
  13149. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13150. * @param depthStencilTexture The depth stencil texture to use to render
  13151. * @param lodLevel defines le lod level to bind to the frame buffer
  13152. */
  13153. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13154. if (lodLevel === void 0) { lodLevel = 0; }
  13155. if (this._currentRenderTarget) {
  13156. this.unBindFramebuffer(this._currentRenderTarget);
  13157. }
  13158. this._currentRenderTarget = texture;
  13159. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13160. var gl = this._gl;
  13161. if (texture.isCube) {
  13162. if (faceIndex === undefined) {
  13163. faceIndex = 0;
  13164. }
  13165. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13166. if (depthStencilTexture) {
  13167. if (depthStencilTexture._generateStencilBuffer) {
  13168. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13169. }
  13170. else {
  13171. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13172. }
  13173. }
  13174. }
  13175. if (this._cachedViewport && !forceFullscreenViewport) {
  13176. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13177. }
  13178. else {
  13179. if (!requiredWidth) {
  13180. requiredWidth = texture.width;
  13181. if (lodLevel) {
  13182. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13183. }
  13184. }
  13185. if (!requiredHeight) {
  13186. requiredHeight = texture.height;
  13187. if (lodLevel) {
  13188. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13189. }
  13190. }
  13191. this._viewport(0, 0, requiredWidth, requiredHeight);
  13192. }
  13193. this.wipeCaches();
  13194. };
  13195. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13196. if (this._currentFramebuffer !== framebuffer) {
  13197. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13198. this._currentFramebuffer = framebuffer;
  13199. }
  13200. };
  13201. /**
  13202. * Unbind the current render target texture from the webGL context
  13203. * @param texture defines the render target texture to unbind
  13204. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13205. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13206. */
  13207. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13208. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13209. this._currentRenderTarget = null;
  13210. // If MSAA, we need to bitblt back to main texture
  13211. var gl = this._gl;
  13212. if (texture._MSAAFramebuffer) {
  13213. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13214. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13215. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13216. }
  13217. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13218. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13219. gl.generateMipmap(gl.TEXTURE_2D);
  13220. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13221. }
  13222. if (onBeforeUnbind) {
  13223. if (texture._MSAAFramebuffer) {
  13224. // Bind the correct framebuffer
  13225. this.bindUnboundFramebuffer(texture._framebuffer);
  13226. }
  13227. onBeforeUnbind();
  13228. }
  13229. this.bindUnboundFramebuffer(null);
  13230. };
  13231. /**
  13232. * Unbind a list of render target textures from the webGL context
  13233. * This is used only when drawBuffer extension or webGL2 are active
  13234. * @param textures defines the render target textures to unbind
  13235. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13236. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13237. */
  13238. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13239. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13240. this._currentRenderTarget = null;
  13241. // If MSAA, we need to bitblt back to main texture
  13242. var gl = this._gl;
  13243. if (textures[0]._MSAAFramebuffer) {
  13244. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13245. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13246. var attachments = textures[0]._attachments;
  13247. if (!attachments) {
  13248. attachments = new Array(textures.length);
  13249. textures[0]._attachments = attachments;
  13250. }
  13251. for (var i = 0; i < textures.length; i++) {
  13252. var texture = textures[i];
  13253. for (var j = 0; j < attachments.length; j++) {
  13254. attachments[j] = gl.NONE;
  13255. }
  13256. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13257. gl.readBuffer(attachments[i]);
  13258. gl.drawBuffers(attachments);
  13259. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13260. }
  13261. for (var i = 0; i < attachments.length; i++) {
  13262. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13263. }
  13264. gl.drawBuffers(attachments);
  13265. }
  13266. for (var i = 0; i < textures.length; i++) {
  13267. var texture = textures[i];
  13268. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13269. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13270. gl.generateMipmap(gl.TEXTURE_2D);
  13271. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13272. }
  13273. }
  13274. if (onBeforeUnbind) {
  13275. if (textures[0]._MSAAFramebuffer) {
  13276. // Bind the correct framebuffer
  13277. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13278. }
  13279. onBeforeUnbind();
  13280. }
  13281. this.bindUnboundFramebuffer(null);
  13282. };
  13283. /**
  13284. * Force the mipmap generation for the given render target texture
  13285. * @param texture defines the render target texture to use
  13286. */
  13287. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13288. if (texture.generateMipMaps) {
  13289. var gl = this._gl;
  13290. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13291. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13292. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13293. }
  13294. };
  13295. /**
  13296. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13297. */
  13298. Engine.prototype.flushFramebuffer = function () {
  13299. this._gl.flush();
  13300. };
  13301. /**
  13302. * Unbind the current render target and bind the default framebuffer
  13303. */
  13304. Engine.prototype.restoreDefaultFramebuffer = function () {
  13305. if (this._currentRenderTarget) {
  13306. this.unBindFramebuffer(this._currentRenderTarget);
  13307. }
  13308. else {
  13309. this.bindUnboundFramebuffer(null);
  13310. }
  13311. if (this._cachedViewport) {
  13312. this.setViewport(this._cachedViewport);
  13313. }
  13314. this.wipeCaches();
  13315. };
  13316. // UBOs
  13317. /**
  13318. * Create an uniform buffer
  13319. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13320. * @param elements defines the content of the uniform buffer
  13321. * @returns the webGL uniform buffer
  13322. */
  13323. Engine.prototype.createUniformBuffer = function (elements) {
  13324. var ubo = this._gl.createBuffer();
  13325. if (!ubo) {
  13326. throw new Error("Unable to create uniform buffer");
  13327. }
  13328. this.bindUniformBuffer(ubo);
  13329. if (elements instanceof Float32Array) {
  13330. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13331. }
  13332. else {
  13333. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13334. }
  13335. this.bindUniformBuffer(null);
  13336. ubo.references = 1;
  13337. return ubo;
  13338. };
  13339. /**
  13340. * Create a dynamic uniform buffer
  13341. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13342. * @param elements defines the content of the uniform buffer
  13343. * @returns the webGL uniform buffer
  13344. */
  13345. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13346. var ubo = this._gl.createBuffer();
  13347. if (!ubo) {
  13348. throw new Error("Unable to create dynamic uniform buffer");
  13349. }
  13350. this.bindUniformBuffer(ubo);
  13351. if (elements instanceof Float32Array) {
  13352. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13353. }
  13354. else {
  13355. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13356. }
  13357. this.bindUniformBuffer(null);
  13358. ubo.references = 1;
  13359. return ubo;
  13360. };
  13361. /**
  13362. * Update an existing uniform buffer
  13363. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13364. * @param uniformBuffer defines the target uniform buffer
  13365. * @param elements defines the content to update
  13366. * @param offset defines the offset in the uniform buffer where update should start
  13367. * @param count defines the size of the data to update
  13368. */
  13369. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13370. this.bindUniformBuffer(uniformBuffer);
  13371. if (offset === undefined) {
  13372. offset = 0;
  13373. }
  13374. if (count === undefined) {
  13375. if (elements instanceof Float32Array) {
  13376. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13377. }
  13378. else {
  13379. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13380. }
  13381. }
  13382. else {
  13383. if (elements instanceof Float32Array) {
  13384. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13385. }
  13386. else {
  13387. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13388. }
  13389. }
  13390. this.bindUniformBuffer(null);
  13391. };
  13392. // VBOs
  13393. Engine.prototype._resetVertexBufferBinding = function () {
  13394. this.bindArrayBuffer(null);
  13395. this._cachedVertexBuffers = null;
  13396. };
  13397. /**
  13398. * Creates a vertex buffer
  13399. * @param data the data for the vertex buffer
  13400. * @returns the new WebGL static buffer
  13401. */
  13402. Engine.prototype.createVertexBuffer = function (data) {
  13403. var vbo = this._gl.createBuffer();
  13404. if (!vbo) {
  13405. throw new Error("Unable to create vertex buffer");
  13406. }
  13407. this.bindArrayBuffer(vbo);
  13408. if (data instanceof Array) {
  13409. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13410. }
  13411. else {
  13412. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13413. }
  13414. this._resetVertexBufferBinding();
  13415. vbo.references = 1;
  13416. return vbo;
  13417. };
  13418. /**
  13419. * Creates a dynamic vertex buffer
  13420. * @param data the data for the dynamic vertex buffer
  13421. * @returns the new WebGL dynamic buffer
  13422. */
  13423. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13424. var vbo = this._gl.createBuffer();
  13425. if (!vbo) {
  13426. throw new Error("Unable to create dynamic vertex buffer");
  13427. }
  13428. this.bindArrayBuffer(vbo);
  13429. if (data instanceof Array) {
  13430. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13431. }
  13432. else {
  13433. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13434. }
  13435. this._resetVertexBufferBinding();
  13436. vbo.references = 1;
  13437. return vbo;
  13438. };
  13439. /**
  13440. * Update a dynamic index buffer
  13441. * @param indexBuffer defines the target index buffer
  13442. * @param indices defines the data to update
  13443. * @param offset defines the offset in the target index buffer where update should start
  13444. */
  13445. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13446. if (offset === void 0) { offset = 0; }
  13447. // Force cache update
  13448. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13449. this.bindIndexBuffer(indexBuffer);
  13450. var arrayBuffer;
  13451. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13452. arrayBuffer = indices;
  13453. }
  13454. else {
  13455. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13456. }
  13457. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13458. this._resetIndexBufferBinding();
  13459. };
  13460. /**
  13461. * Updates a dynamic vertex buffer.
  13462. * @param vertexBuffer the vertex buffer to update
  13463. * @param data the data used to update the vertex buffer
  13464. * @param byteOffset the byte offset of the data
  13465. * @param byteLength the byte length of the data
  13466. */
  13467. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13468. this.bindArrayBuffer(vertexBuffer);
  13469. if (byteOffset === undefined) {
  13470. byteOffset = 0;
  13471. }
  13472. if (byteLength === undefined) {
  13473. if (data instanceof Array) {
  13474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13475. }
  13476. else {
  13477. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13478. }
  13479. }
  13480. else {
  13481. if (data instanceof Array) {
  13482. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13483. }
  13484. else {
  13485. if (data instanceof ArrayBuffer) {
  13486. data = new Uint8Array(data, byteOffset, byteLength);
  13487. }
  13488. else {
  13489. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13490. }
  13491. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13492. }
  13493. }
  13494. this._resetVertexBufferBinding();
  13495. };
  13496. Engine.prototype._resetIndexBufferBinding = function () {
  13497. this.bindIndexBuffer(null);
  13498. this._cachedIndexBuffer = null;
  13499. };
  13500. /**
  13501. * Creates a new index buffer
  13502. * @param indices defines the content of the index buffer
  13503. * @param updatable defines if the index buffer must be updatable
  13504. * @returns a new webGL buffer
  13505. */
  13506. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13507. var vbo = this._gl.createBuffer();
  13508. if (!vbo) {
  13509. throw new Error("Unable to create index buffer");
  13510. }
  13511. this.bindIndexBuffer(vbo);
  13512. // Check for 32 bits indices
  13513. var arrayBuffer;
  13514. var need32Bits = false;
  13515. if (indices instanceof Uint16Array) {
  13516. arrayBuffer = indices;
  13517. }
  13518. else {
  13519. //check 32 bit support
  13520. if (this._caps.uintIndices) {
  13521. if (indices instanceof Uint32Array) {
  13522. arrayBuffer = indices;
  13523. need32Bits = true;
  13524. }
  13525. else {
  13526. //number[] or Int32Array, check if 32 bit is necessary
  13527. for (var index = 0; index < indices.length; index++) {
  13528. if (indices[index] > 65535) {
  13529. need32Bits = true;
  13530. break;
  13531. }
  13532. }
  13533. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13534. }
  13535. }
  13536. else {
  13537. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13538. arrayBuffer = new Uint16Array(indices);
  13539. }
  13540. }
  13541. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13542. this._resetIndexBufferBinding();
  13543. vbo.references = 1;
  13544. vbo.is32Bits = need32Bits;
  13545. return vbo;
  13546. };
  13547. /**
  13548. * Bind a webGL buffer to the webGL context
  13549. * @param buffer defines the buffer to bind
  13550. */
  13551. Engine.prototype.bindArrayBuffer = function (buffer) {
  13552. if (!this._vaoRecordInProgress) {
  13553. this._unbindVertexArrayObject();
  13554. }
  13555. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13556. };
  13557. /**
  13558. * Bind an uniform buffer to the current webGL context
  13559. * @param buffer defines the buffer to bind
  13560. */
  13561. Engine.prototype.bindUniformBuffer = function (buffer) {
  13562. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13563. };
  13564. /**
  13565. * Bind a buffer to the current webGL context at a given location
  13566. * @param buffer defines the buffer to bind
  13567. * @param location defines the index where to bind the buffer
  13568. */
  13569. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13570. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13571. };
  13572. /**
  13573. * Bind a specific block at a given index in a specific shader program
  13574. * @param shaderProgram defines the shader program
  13575. * @param blockName defines the block name
  13576. * @param index defines the index where to bind the block
  13577. */
  13578. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13579. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13580. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13581. };
  13582. ;
  13583. Engine.prototype.bindIndexBuffer = function (buffer) {
  13584. if (!this._vaoRecordInProgress) {
  13585. this._unbindVertexArrayObject();
  13586. }
  13587. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13588. };
  13589. Engine.prototype.bindBuffer = function (buffer, target) {
  13590. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13591. this._gl.bindBuffer(target, buffer);
  13592. this._currentBoundBuffer[target] = buffer;
  13593. }
  13594. };
  13595. /**
  13596. * update the bound buffer with the given data
  13597. * @param data defines the data to update
  13598. */
  13599. Engine.prototype.updateArrayBuffer = function (data) {
  13600. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13601. };
  13602. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13603. var pointer = this._currentBufferPointers[indx];
  13604. var changed = false;
  13605. if (!pointer.active) {
  13606. changed = true;
  13607. pointer.active = true;
  13608. pointer.index = indx;
  13609. pointer.size = size;
  13610. pointer.type = type;
  13611. pointer.normalized = normalized;
  13612. pointer.stride = stride;
  13613. pointer.offset = offset;
  13614. pointer.buffer = buffer;
  13615. }
  13616. else {
  13617. if (pointer.buffer !== buffer) {
  13618. pointer.buffer = buffer;
  13619. changed = true;
  13620. }
  13621. if (pointer.size !== size) {
  13622. pointer.size = size;
  13623. changed = true;
  13624. }
  13625. if (pointer.type !== type) {
  13626. pointer.type = type;
  13627. changed = true;
  13628. }
  13629. if (pointer.normalized !== normalized) {
  13630. pointer.normalized = normalized;
  13631. changed = true;
  13632. }
  13633. if (pointer.stride !== stride) {
  13634. pointer.stride = stride;
  13635. changed = true;
  13636. }
  13637. if (pointer.offset !== offset) {
  13638. pointer.offset = offset;
  13639. changed = true;
  13640. }
  13641. }
  13642. if (changed || this._vaoRecordInProgress) {
  13643. this.bindArrayBuffer(buffer);
  13644. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13645. }
  13646. };
  13647. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13648. if (indexBuffer == null) {
  13649. return;
  13650. }
  13651. if (this._cachedIndexBuffer !== indexBuffer) {
  13652. this._cachedIndexBuffer = indexBuffer;
  13653. this.bindIndexBuffer(indexBuffer);
  13654. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13655. }
  13656. };
  13657. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13658. var attributes = effect.getAttributesNames();
  13659. if (!this._vaoRecordInProgress) {
  13660. this._unbindVertexArrayObject();
  13661. }
  13662. this.unbindAllAttributes();
  13663. for (var index = 0; index < attributes.length; index++) {
  13664. var order = effect.getAttributeLocation(index);
  13665. if (order >= 0) {
  13666. var vertexBuffer = vertexBuffers[attributes[index]];
  13667. if (!vertexBuffer) {
  13668. continue;
  13669. }
  13670. this._gl.enableVertexAttribArray(order);
  13671. if (!this._vaoRecordInProgress) {
  13672. this._vertexAttribArraysEnabled[order] = true;
  13673. }
  13674. var buffer = vertexBuffer.getBuffer();
  13675. if (buffer) {
  13676. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13677. if (vertexBuffer.getIsInstanced()) {
  13678. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13679. if (!this._vaoRecordInProgress) {
  13680. this._currentInstanceLocations.push(order);
  13681. this._currentInstanceBuffers.push(buffer);
  13682. }
  13683. }
  13684. }
  13685. }
  13686. }
  13687. };
  13688. /**
  13689. * Records a vertex array object
  13690. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13691. * @param vertexBuffers defines the list of vertex buffers to store
  13692. * @param indexBuffer defines the index buffer to store
  13693. * @param effect defines the effect to store
  13694. * @returns the new vertex array object
  13695. */
  13696. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13697. var vao = this._gl.createVertexArray();
  13698. this._vaoRecordInProgress = true;
  13699. this._gl.bindVertexArray(vao);
  13700. this._mustWipeVertexAttributes = true;
  13701. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13702. this.bindIndexBuffer(indexBuffer);
  13703. this._vaoRecordInProgress = false;
  13704. this._gl.bindVertexArray(null);
  13705. return vao;
  13706. };
  13707. /**
  13708. * Bind a specific vertex array object
  13709. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13710. * @param vertexArrayObject defines the vertex array object to bind
  13711. * @param indexBuffer defines the index buffer to bind
  13712. */
  13713. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13714. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13715. this._cachedVertexArrayObject = vertexArrayObject;
  13716. this._gl.bindVertexArray(vertexArrayObject);
  13717. this._cachedVertexBuffers = null;
  13718. this._cachedIndexBuffer = null;
  13719. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13720. this._mustWipeVertexAttributes = true;
  13721. }
  13722. };
  13723. /**
  13724. * Bind webGl buffers directly to the webGL context
  13725. * @param vertexBuffer defines the vertex buffer to bind
  13726. * @param indexBuffer defines the index buffer to bind
  13727. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13728. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13729. * @param effect defines the effect associated with the vertex buffer
  13730. */
  13731. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13732. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13733. this._cachedVertexBuffers = vertexBuffer;
  13734. this._cachedEffectForVertexBuffers = effect;
  13735. var attributesCount = effect.getAttributesCount();
  13736. this._unbindVertexArrayObject();
  13737. this.unbindAllAttributes();
  13738. var offset = 0;
  13739. for (var index = 0; index < attributesCount; index++) {
  13740. if (index < vertexDeclaration.length) {
  13741. var order = effect.getAttributeLocation(index);
  13742. if (order >= 0) {
  13743. this._gl.enableVertexAttribArray(order);
  13744. this._vertexAttribArraysEnabled[order] = true;
  13745. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13746. }
  13747. offset += vertexDeclaration[index] * 4;
  13748. }
  13749. }
  13750. }
  13751. this._bindIndexBufferWithCache(indexBuffer);
  13752. };
  13753. Engine.prototype._unbindVertexArrayObject = function () {
  13754. if (!this._cachedVertexArrayObject) {
  13755. return;
  13756. }
  13757. this._cachedVertexArrayObject = null;
  13758. this._gl.bindVertexArray(null);
  13759. };
  13760. /**
  13761. * Bind a list of vertex buffers to the webGL context
  13762. * @param vertexBuffers defines the list of vertex buffers to bind
  13763. * @param indexBuffer defines the index buffer to bind
  13764. * @param effect defines the effect associated with the vertex buffers
  13765. */
  13766. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13767. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13768. this._cachedVertexBuffers = vertexBuffers;
  13769. this._cachedEffectForVertexBuffers = effect;
  13770. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13771. }
  13772. this._bindIndexBufferWithCache(indexBuffer);
  13773. };
  13774. /**
  13775. * Unbind all instance attributes
  13776. */
  13777. Engine.prototype.unbindInstanceAttributes = function () {
  13778. var boundBuffer;
  13779. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13780. var instancesBuffer = this._currentInstanceBuffers[i];
  13781. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13782. boundBuffer = instancesBuffer;
  13783. this.bindArrayBuffer(instancesBuffer);
  13784. }
  13785. var offsetLocation = this._currentInstanceLocations[i];
  13786. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13787. }
  13788. this._currentInstanceBuffers.length = 0;
  13789. this._currentInstanceLocations.length = 0;
  13790. };
  13791. /**
  13792. * Release and free the memory of a vertex array object
  13793. * @param vao defines the vertex array object to delete
  13794. */
  13795. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13796. this._gl.deleteVertexArray(vao);
  13797. };
  13798. /** @hidden */
  13799. Engine.prototype._releaseBuffer = function (buffer) {
  13800. buffer.references--;
  13801. if (buffer.references === 0) {
  13802. this._gl.deleteBuffer(buffer);
  13803. return true;
  13804. }
  13805. return false;
  13806. };
  13807. /**
  13808. * Creates a webGL buffer to use with instanciation
  13809. * @param capacity defines the size of the buffer
  13810. * @returns the webGL buffer
  13811. */
  13812. Engine.prototype.createInstancesBuffer = function (capacity) {
  13813. var buffer = this._gl.createBuffer();
  13814. if (!buffer) {
  13815. throw new Error("Unable to create instance buffer");
  13816. }
  13817. buffer.capacity = capacity;
  13818. this.bindArrayBuffer(buffer);
  13819. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13820. return buffer;
  13821. };
  13822. /**
  13823. * Delete a webGL buffer used with instanciation
  13824. * @param buffer defines the webGL buffer to delete
  13825. */
  13826. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13827. this._gl.deleteBuffer(buffer);
  13828. };
  13829. /**
  13830. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13831. * @param instancesBuffer defines the webGL buffer to update and bind
  13832. * @param data defines the data to store in the buffer
  13833. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13834. */
  13835. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13836. this.bindArrayBuffer(instancesBuffer);
  13837. if (data) {
  13838. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13839. }
  13840. if (offsetLocations[0].index !== undefined) {
  13841. var stride = 0;
  13842. for (var i = 0; i < offsetLocations.length; i++) {
  13843. var ai = offsetLocations[i];
  13844. stride += ai.attributeSize * 4;
  13845. }
  13846. for (var i = 0; i < offsetLocations.length; i++) {
  13847. var ai = offsetLocations[i];
  13848. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13849. this._gl.enableVertexAttribArray(ai.index);
  13850. this._vertexAttribArraysEnabled[ai.index] = true;
  13851. }
  13852. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13853. this._gl.vertexAttribDivisor(ai.index, 1);
  13854. this._currentInstanceLocations.push(ai.index);
  13855. this._currentInstanceBuffers.push(instancesBuffer);
  13856. }
  13857. }
  13858. else {
  13859. for (var index = 0; index < 4; index++) {
  13860. var offsetLocation = offsetLocations[index];
  13861. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13862. this._gl.enableVertexAttribArray(offsetLocation);
  13863. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13864. }
  13865. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13866. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13867. this._currentInstanceLocations.push(offsetLocation);
  13868. this._currentInstanceBuffers.push(instancesBuffer);
  13869. }
  13870. }
  13871. };
  13872. /**
  13873. * Apply all cached states (depth, culling, stencil and alpha)
  13874. */
  13875. Engine.prototype.applyStates = function () {
  13876. this._depthCullingState.apply(this._gl);
  13877. this._stencilState.apply(this._gl);
  13878. this._alphaState.apply(this._gl);
  13879. };
  13880. /**
  13881. * Send a draw order
  13882. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13883. * @param indexStart defines the starting index
  13884. * @param indexCount defines the number of index to draw
  13885. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13886. */
  13887. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13888. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13889. };
  13890. /**
  13891. * Draw a list of points
  13892. * @param verticesStart defines the index of first vertex to draw
  13893. * @param verticesCount defines the count of vertices to draw
  13894. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13895. */
  13896. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13897. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13898. };
  13899. /**
  13900. * Draw a list of unindexed primitives
  13901. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13902. * @param verticesStart defines the index of first vertex to draw
  13903. * @param verticesCount defines the count of vertices to draw
  13904. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13905. */
  13906. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13907. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13908. };
  13909. /**
  13910. * Draw a list of indexed primitives
  13911. * @param fillMode defines the primitive to use
  13912. * @param indexStart defines the starting index
  13913. * @param indexCount defines the number of index to draw
  13914. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13915. */
  13916. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13917. // Apply states
  13918. this.applyStates();
  13919. this._drawCalls.addCount(1, false);
  13920. // Render
  13921. var drawMode = this._drawMode(fillMode);
  13922. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13923. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13924. if (instancesCount) {
  13925. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13926. }
  13927. else {
  13928. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13929. }
  13930. };
  13931. /**
  13932. * Draw a list of unindexed primitives
  13933. * @param fillMode defines the primitive to use
  13934. * @param verticesStart defines the index of first vertex to draw
  13935. * @param verticesCount defines the count of vertices to draw
  13936. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13937. */
  13938. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13939. // Apply states
  13940. this.applyStates();
  13941. this._drawCalls.addCount(1, false);
  13942. var drawMode = this._drawMode(fillMode);
  13943. if (instancesCount) {
  13944. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13945. }
  13946. else {
  13947. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13948. }
  13949. };
  13950. Engine.prototype._drawMode = function (fillMode) {
  13951. switch (fillMode) {
  13952. // Triangle views
  13953. case BABYLON.Material.TriangleFillMode:
  13954. return this._gl.TRIANGLES;
  13955. case BABYLON.Material.PointFillMode:
  13956. return this._gl.POINTS;
  13957. case BABYLON.Material.WireFrameFillMode:
  13958. return this._gl.LINES;
  13959. // Draw modes
  13960. case BABYLON.Material.PointListDrawMode:
  13961. return this._gl.POINTS;
  13962. case BABYLON.Material.LineListDrawMode:
  13963. return this._gl.LINES;
  13964. case BABYLON.Material.LineLoopDrawMode:
  13965. return this._gl.LINE_LOOP;
  13966. case BABYLON.Material.LineStripDrawMode:
  13967. return this._gl.LINE_STRIP;
  13968. case BABYLON.Material.TriangleStripDrawMode:
  13969. return this._gl.TRIANGLE_STRIP;
  13970. case BABYLON.Material.TriangleFanDrawMode:
  13971. return this._gl.TRIANGLE_FAN;
  13972. default:
  13973. return this._gl.TRIANGLES;
  13974. }
  13975. };
  13976. // Shaders
  13977. /** @hidden */
  13978. Engine.prototype._releaseEffect = function (effect) {
  13979. if (this._compiledEffects[effect._key]) {
  13980. delete this._compiledEffects[effect._key];
  13981. this._deleteProgram(effect.getProgram());
  13982. }
  13983. };
  13984. /** @hidden */
  13985. Engine.prototype._deleteProgram = function (program) {
  13986. if (program) {
  13987. program.__SPECTOR_rebuildProgram = null;
  13988. if (program.transformFeedback) {
  13989. this.deleteTransformFeedback(program.transformFeedback);
  13990. program.transformFeedback = null;
  13991. }
  13992. this._gl.deleteProgram(program);
  13993. }
  13994. };
  13995. /**
  13996. * Create a new effect (used to store vertex/fragment shaders)
  13997. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13998. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13999. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14000. * @param samplers defines an array of string used to represent textures
  14001. * @param defines defines the string containing the defines to use to compile the shaders
  14002. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14003. * @param onCompiled defines a function to call when the effect creation is successful
  14004. * @param onError defines a function to call when the effect creation has failed
  14005. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14006. * @returns the new Effect
  14007. */
  14008. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14009. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14010. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14011. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14012. if (this._compiledEffects[name]) {
  14013. var compiledEffect = this._compiledEffects[name];
  14014. if (onCompiled && compiledEffect.isReady()) {
  14015. onCompiled(compiledEffect);
  14016. }
  14017. return compiledEffect;
  14018. }
  14019. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14020. effect._key = name;
  14021. this._compiledEffects[name] = effect;
  14022. return effect;
  14023. };
  14024. /**
  14025. * Directly creates a webGL program
  14026. * @param vertexCode defines the vertex shader code to use
  14027. * @param fragmentCode defines the fragment shader code to use
  14028. * @param context defines the webGL context to use (if not set, the current one will be used)
  14029. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14030. * @returns the new webGL program
  14031. */
  14032. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14033. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14034. context = context || this._gl;
  14035. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14036. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14037. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14038. };
  14039. /**
  14040. * Creates a webGL program
  14041. * @param vertexCode defines the vertex shader code to use
  14042. * @param fragmentCode defines the fragment shader code to use
  14043. * @param defines defines the string containing the defines to use to compile the shaders
  14044. * @param context defines the webGL context to use (if not set, the current one will be used)
  14045. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14046. * @returns the new webGL program
  14047. */
  14048. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14049. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14050. context = context || this._gl;
  14051. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14052. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14053. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14054. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14055. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14056. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14057. return program;
  14058. };
  14059. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14060. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14061. var shaderProgram = context.createProgram();
  14062. if (!shaderProgram) {
  14063. throw new Error("Unable to create program");
  14064. }
  14065. context.attachShader(shaderProgram, vertexShader);
  14066. context.attachShader(shaderProgram, fragmentShader);
  14067. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14068. var transformFeedback = this.createTransformFeedback();
  14069. this.bindTransformFeedback(transformFeedback);
  14070. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14071. shaderProgram.transformFeedback = transformFeedback;
  14072. }
  14073. context.linkProgram(shaderProgram);
  14074. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14075. this.bindTransformFeedback(null);
  14076. }
  14077. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14078. if (!linked) {
  14079. var error = context.getProgramInfoLog(shaderProgram);
  14080. if (error) {
  14081. throw new Error(error);
  14082. }
  14083. }
  14084. if (this.validateShaderPrograms) {
  14085. context.validateProgram(shaderProgram);
  14086. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14087. if (!validated) {
  14088. var error = context.getProgramInfoLog(shaderProgram);
  14089. if (error) {
  14090. throw new Error(error);
  14091. }
  14092. }
  14093. }
  14094. context.deleteShader(vertexShader);
  14095. context.deleteShader(fragmentShader);
  14096. return shaderProgram;
  14097. };
  14098. /**
  14099. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14100. * @param shaderProgram defines the webGL program to use
  14101. * @param uniformsNames defines the list of uniform names
  14102. * @returns an array of webGL uniform locations
  14103. */
  14104. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14105. var results = new Array();
  14106. for (var index = 0; index < uniformsNames.length; index++) {
  14107. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14108. }
  14109. return results;
  14110. };
  14111. /**
  14112. * Gets the lsit of active attributes for a given webGL program
  14113. * @param shaderProgram defines the webGL program to use
  14114. * @param attributesNames defines the list of attribute names to get
  14115. * @returns an array of indices indicating the offset of each attribute
  14116. */
  14117. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14118. var results = [];
  14119. for (var index = 0; index < attributesNames.length; index++) {
  14120. try {
  14121. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14122. }
  14123. catch (e) {
  14124. results.push(-1);
  14125. }
  14126. }
  14127. return results;
  14128. };
  14129. /**
  14130. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14131. * @param effect defines the effect to activate
  14132. */
  14133. Engine.prototype.enableEffect = function (effect) {
  14134. if (!effect) {
  14135. return;
  14136. }
  14137. // Use program
  14138. this.bindSamplers(effect);
  14139. this._currentEffect = effect;
  14140. if (effect.onBind) {
  14141. effect.onBind(effect);
  14142. }
  14143. effect.onBindObservable.notifyObservers(effect);
  14144. };
  14145. /**
  14146. * Set the value of an uniform to an array of int32
  14147. * @param uniform defines the webGL uniform location where to store the value
  14148. * @param array defines the array of int32 to store
  14149. */
  14150. Engine.prototype.setIntArray = function (uniform, array) {
  14151. if (!uniform)
  14152. return;
  14153. this._gl.uniform1iv(uniform, array);
  14154. };
  14155. /**
  14156. * Set the value of an uniform to an array of int32 (stored as vec2)
  14157. * @param uniform defines the webGL uniform location where to store the value
  14158. * @param array defines the array of int32 to store
  14159. */
  14160. Engine.prototype.setIntArray2 = function (uniform, array) {
  14161. if (!uniform || array.length % 2 !== 0)
  14162. return;
  14163. this._gl.uniform2iv(uniform, array);
  14164. };
  14165. /**
  14166. * Set the value of an uniform to an array of int32 (stored as vec3)
  14167. * @param uniform defines the webGL uniform location where to store the value
  14168. * @param array defines the array of int32 to store
  14169. */
  14170. Engine.prototype.setIntArray3 = function (uniform, array) {
  14171. if (!uniform || array.length % 3 !== 0)
  14172. return;
  14173. this._gl.uniform3iv(uniform, array);
  14174. };
  14175. /**
  14176. * Set the value of an uniform to an array of int32 (stored as vec4)
  14177. * @param uniform defines the webGL uniform location where to store the value
  14178. * @param array defines the array of int32 to store
  14179. */
  14180. Engine.prototype.setIntArray4 = function (uniform, array) {
  14181. if (!uniform || array.length % 4 !== 0)
  14182. return;
  14183. this._gl.uniform4iv(uniform, array);
  14184. };
  14185. /**
  14186. * Set the value of an uniform to an array of float32
  14187. * @param uniform defines the webGL uniform location where to store the value
  14188. * @param array defines the array of float32 to store
  14189. */
  14190. Engine.prototype.setFloatArray = function (uniform, array) {
  14191. if (!uniform)
  14192. return;
  14193. this._gl.uniform1fv(uniform, array);
  14194. };
  14195. /**
  14196. * Set the value of an uniform to an array of float32 (stored as vec2)
  14197. * @param uniform defines the webGL uniform location where to store the value
  14198. * @param array defines the array of float32 to store
  14199. */
  14200. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14201. if (!uniform || array.length % 2 !== 0)
  14202. return;
  14203. this._gl.uniform2fv(uniform, array);
  14204. };
  14205. /**
  14206. * Set the value of an uniform to an array of float32 (stored as vec3)
  14207. * @param uniform defines the webGL uniform location where to store the value
  14208. * @param array defines the array of float32 to store
  14209. */
  14210. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14211. if (!uniform || array.length % 3 !== 0)
  14212. return;
  14213. this._gl.uniform3fv(uniform, array);
  14214. };
  14215. /**
  14216. * Set the value of an uniform to an array of float32 (stored as vec4)
  14217. * @param uniform defines the webGL uniform location where to store the value
  14218. * @param array defines the array of float32 to store
  14219. */
  14220. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14221. if (!uniform || array.length % 4 !== 0)
  14222. return;
  14223. this._gl.uniform4fv(uniform, array);
  14224. };
  14225. /**
  14226. * Set the value of an uniform to an array of number
  14227. * @param uniform defines the webGL uniform location where to store the value
  14228. * @param array defines the array of number to store
  14229. */
  14230. Engine.prototype.setArray = function (uniform, array) {
  14231. if (!uniform)
  14232. return;
  14233. this._gl.uniform1fv(uniform, array);
  14234. };
  14235. /**
  14236. * Set the value of an uniform to an array of number (stored as vec2)
  14237. * @param uniform defines the webGL uniform location where to store the value
  14238. * @param array defines the array of number to store
  14239. */
  14240. Engine.prototype.setArray2 = function (uniform, array) {
  14241. if (!uniform || array.length % 2 !== 0)
  14242. return;
  14243. this._gl.uniform2fv(uniform, array);
  14244. };
  14245. /**
  14246. * Set the value of an uniform to an array of number (stored as vec3)
  14247. * @param uniform defines the webGL uniform location where to store the value
  14248. * @param array defines the array of number to store
  14249. */
  14250. Engine.prototype.setArray3 = function (uniform, array) {
  14251. if (!uniform || array.length % 3 !== 0)
  14252. return;
  14253. this._gl.uniform3fv(uniform, array);
  14254. };
  14255. /**
  14256. * Set the value of an uniform to an array of number (stored as vec4)
  14257. * @param uniform defines the webGL uniform location where to store the value
  14258. * @param array defines the array of number to store
  14259. */
  14260. Engine.prototype.setArray4 = function (uniform, array) {
  14261. if (!uniform || array.length % 4 !== 0)
  14262. return;
  14263. this._gl.uniform4fv(uniform, array);
  14264. };
  14265. /**
  14266. * Set the value of an uniform to an array of float32 (stored as matrices)
  14267. * @param uniform defines the webGL uniform location where to store the value
  14268. * @param matrices defines the array of float32 to store
  14269. */
  14270. Engine.prototype.setMatrices = function (uniform, matrices) {
  14271. if (!uniform)
  14272. return;
  14273. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14274. };
  14275. /**
  14276. * Set the value of an uniform to a matrix
  14277. * @param uniform defines the webGL uniform location where to store the value
  14278. * @param matrix defines the matrix to store
  14279. */
  14280. Engine.prototype.setMatrix = function (uniform, matrix) {
  14281. if (!uniform)
  14282. return;
  14283. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14284. };
  14285. /**
  14286. * Set the value of an uniform to a matrix (3x3)
  14287. * @param uniform defines the webGL uniform location where to store the value
  14288. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14289. */
  14290. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14291. if (!uniform)
  14292. return;
  14293. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14294. };
  14295. /**
  14296. * Set the value of an uniform to a matrix (2x2)
  14297. * @param uniform defines the webGL uniform location where to store the value
  14298. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14299. */
  14300. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14301. if (!uniform)
  14302. return;
  14303. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14304. };
  14305. /**
  14306. * Set the value of an uniform to a number (int)
  14307. * @param uniform defines the webGL uniform location where to store the value
  14308. * @param value defines the int number to store
  14309. */
  14310. Engine.prototype.setInt = function (uniform, value) {
  14311. if (!uniform)
  14312. return;
  14313. this._gl.uniform1i(uniform, value);
  14314. };
  14315. /**
  14316. * Set the value of an uniform to a number (float)
  14317. * @param uniform defines the webGL uniform location where to store the value
  14318. * @param value defines the float number to store
  14319. */
  14320. Engine.prototype.setFloat = function (uniform, value) {
  14321. if (!uniform)
  14322. return;
  14323. this._gl.uniform1f(uniform, value);
  14324. };
  14325. /**
  14326. * Set the value of an uniform to a vec2
  14327. * @param uniform defines the webGL uniform location where to store the value
  14328. * @param x defines the 1st component of the value
  14329. * @param y defines the 2nd component of the value
  14330. */
  14331. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14332. if (!uniform)
  14333. return;
  14334. this._gl.uniform2f(uniform, x, y);
  14335. };
  14336. /**
  14337. * Set the value of an uniform to a vec3
  14338. * @param uniform defines the webGL uniform location where to store the value
  14339. * @param x defines the 1st component of the value
  14340. * @param y defines the 2nd component of the value
  14341. * @param z defines the 3rd component of the value
  14342. */
  14343. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14344. if (!uniform)
  14345. return;
  14346. this._gl.uniform3f(uniform, x, y, z);
  14347. };
  14348. /**
  14349. * Set the value of an uniform to a boolean
  14350. * @param uniform defines the webGL uniform location where to store the value
  14351. * @param bool defines the boolean to store
  14352. */
  14353. Engine.prototype.setBool = function (uniform, bool) {
  14354. if (!uniform)
  14355. return;
  14356. this._gl.uniform1i(uniform, bool);
  14357. };
  14358. /**
  14359. * Set the value of an uniform to a vec4
  14360. * @param uniform defines the webGL uniform location where to store the value
  14361. * @param x defines the 1st component of the value
  14362. * @param y defines the 2nd component of the value
  14363. * @param z defines the 3rd component of the value
  14364. * @param w defines the 4th component of the value
  14365. */
  14366. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14367. if (!uniform)
  14368. return;
  14369. this._gl.uniform4f(uniform, x, y, z, w);
  14370. };
  14371. /**
  14372. * Set the value of an uniform to a Color3
  14373. * @param uniform defines the webGL uniform location where to store the value
  14374. * @param color3 defines the color to store
  14375. */
  14376. Engine.prototype.setColor3 = function (uniform, color3) {
  14377. if (!uniform)
  14378. return;
  14379. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14380. };
  14381. /**
  14382. * Set the value of an uniform to a Color3 and an alpha value
  14383. * @param uniform defines the webGL uniform location where to store the value
  14384. * @param color3 defines the color to store
  14385. * @param alpha defines the alpha component to store
  14386. */
  14387. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14388. if (!uniform)
  14389. return;
  14390. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14391. };
  14392. /**
  14393. * Sets a Color4 on a uniform variable
  14394. * @param uniform defines the uniform location
  14395. * @param color4 defines the value to be set
  14396. */
  14397. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14398. if (!uniform)
  14399. return;
  14400. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14401. };
  14402. // States
  14403. /**
  14404. * Set various states to the webGL context
  14405. * @param culling defines backface culling state
  14406. * @param zOffset defines the value to apply to zOffset (0 by default)
  14407. * @param force defines if states must be applied even if cache is up to date
  14408. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14409. */
  14410. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14411. if (zOffset === void 0) { zOffset = 0; }
  14412. if (reverseSide === void 0) { reverseSide = false; }
  14413. // Culling
  14414. if (this._depthCullingState.cull !== culling || force) {
  14415. this._depthCullingState.cull = culling;
  14416. }
  14417. // Cull face
  14418. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14419. if (this._depthCullingState.cullFace !== cullFace || force) {
  14420. this._depthCullingState.cullFace = cullFace;
  14421. }
  14422. // Z offset
  14423. this.setZOffset(zOffset);
  14424. // Front face
  14425. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14426. if (this._depthCullingState.frontFace !== frontFace || force) {
  14427. this._depthCullingState.frontFace = frontFace;
  14428. }
  14429. };
  14430. /**
  14431. * Set the z offset to apply to current rendering
  14432. * @param value defines the offset to apply
  14433. */
  14434. Engine.prototype.setZOffset = function (value) {
  14435. this._depthCullingState.zOffset = value;
  14436. };
  14437. /**
  14438. * Gets the current value of the zOffset
  14439. * @returns the current zOffset state
  14440. */
  14441. Engine.prototype.getZOffset = function () {
  14442. return this._depthCullingState.zOffset;
  14443. };
  14444. /**
  14445. * Enable or disable depth buffering
  14446. * @param enable defines the state to set
  14447. */
  14448. Engine.prototype.setDepthBuffer = function (enable) {
  14449. this._depthCullingState.depthTest = enable;
  14450. };
  14451. /**
  14452. * Gets a boolean indicating if depth writing is enabled
  14453. * @returns the current depth writing state
  14454. */
  14455. Engine.prototype.getDepthWrite = function () {
  14456. return this._depthCullingState.depthMask;
  14457. };
  14458. /**
  14459. * Enable or disable depth writing
  14460. * @param enable defines the state to set
  14461. */
  14462. Engine.prototype.setDepthWrite = function (enable) {
  14463. this._depthCullingState.depthMask = enable;
  14464. };
  14465. /**
  14466. * Enable or disable color writing
  14467. * @param enable defines the state to set
  14468. */
  14469. Engine.prototype.setColorWrite = function (enable) {
  14470. this._gl.colorMask(enable, enable, enable, enable);
  14471. this._colorWrite = enable;
  14472. };
  14473. /**
  14474. * Gets a boolean indicating if color writing is enabled
  14475. * @returns the current color writing state
  14476. */
  14477. Engine.prototype.getColorWrite = function () {
  14478. return this._colorWrite;
  14479. };
  14480. /**
  14481. * Sets alpha constants used by some alpha blending modes
  14482. * @param r defines the red component
  14483. * @param g defines the green component
  14484. * @param b defines the blue component
  14485. * @param a defines the alpha component
  14486. */
  14487. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14488. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14489. };
  14490. /**
  14491. * Sets the current alpha mode
  14492. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14493. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14494. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14495. */
  14496. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14497. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14498. if (this._alphaMode === mode) {
  14499. return;
  14500. }
  14501. switch (mode) {
  14502. case Engine.ALPHA_DISABLE:
  14503. this._alphaState.alphaBlend = false;
  14504. break;
  14505. case Engine.ALPHA_PREMULTIPLIED:
  14506. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14507. this._alphaState.alphaBlend = true;
  14508. break;
  14509. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14510. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14511. this._alphaState.alphaBlend = true;
  14512. break;
  14513. case Engine.ALPHA_COMBINE:
  14514. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14515. this._alphaState.alphaBlend = true;
  14516. break;
  14517. case Engine.ALPHA_ONEONE:
  14518. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14519. this._alphaState.alphaBlend = true;
  14520. break;
  14521. case Engine.ALPHA_ADD:
  14522. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14523. this._alphaState.alphaBlend = true;
  14524. break;
  14525. case Engine.ALPHA_SUBTRACT:
  14526. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14527. this._alphaState.alphaBlend = true;
  14528. break;
  14529. case Engine.ALPHA_MULTIPLY:
  14530. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14531. this._alphaState.alphaBlend = true;
  14532. break;
  14533. case Engine.ALPHA_MAXIMIZED:
  14534. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14535. this._alphaState.alphaBlend = true;
  14536. break;
  14537. case Engine.ALPHA_INTERPOLATE:
  14538. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14539. this._alphaState.alphaBlend = true;
  14540. break;
  14541. case Engine.ALPHA_SCREENMODE:
  14542. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14543. this._alphaState.alphaBlend = true;
  14544. break;
  14545. }
  14546. if (!noDepthWriteChange) {
  14547. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14548. }
  14549. this._alphaMode = mode;
  14550. };
  14551. /**
  14552. * Gets the current alpha mode
  14553. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14554. * @returns the current alpha mode
  14555. */
  14556. Engine.prototype.getAlphaMode = function () {
  14557. return this._alphaMode;
  14558. };
  14559. // Textures
  14560. /**
  14561. * Clears the list of texture accessible through engine.
  14562. * This can help preventing texture load conflict due to name collision.
  14563. */
  14564. Engine.prototype.clearInternalTexturesCache = function () {
  14565. this._internalTexturesCache = [];
  14566. };
  14567. /**
  14568. * Force the entire cache to be cleared
  14569. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14570. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14571. */
  14572. Engine.prototype.wipeCaches = function (bruteForce) {
  14573. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14574. return;
  14575. }
  14576. this._currentEffect = null;
  14577. this._unpackFlipYCached = null;
  14578. this._viewportCached.x = 0;
  14579. this._viewportCached.y = 0;
  14580. this._viewportCached.z = 0;
  14581. this._viewportCached.w = 0;
  14582. if (bruteForce) {
  14583. this.resetTextureCache();
  14584. this._currentProgram = null;
  14585. this._stencilState.reset();
  14586. this._depthCullingState.reset();
  14587. this.setDepthFunctionToLessOrEqual();
  14588. this._alphaState.reset();
  14589. }
  14590. this._resetVertexBufferBinding();
  14591. this._cachedIndexBuffer = null;
  14592. this._cachedEffectForVertexBuffers = null;
  14593. this._unbindVertexArrayObject();
  14594. this.bindIndexBuffer(null);
  14595. };
  14596. /**
  14597. * Set the compressed texture format to use, based on the formats you have, and the formats
  14598. * supported by the hardware / browser.
  14599. *
  14600. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14601. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14602. * to API arguments needed to compressed textures. This puts the burden on the container
  14603. * generator to house the arcane code for determining these for current & future formats.
  14604. *
  14605. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14606. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14607. *
  14608. * Note: The result of this call is not taken into account when a texture is base64.
  14609. *
  14610. * @param formatsAvailable defines the list of those format families you have created
  14611. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14612. *
  14613. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14614. * @returns The extension selected.
  14615. */
  14616. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14617. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14618. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14619. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14620. return this._textureFormatInUse = this._texturesSupported[i];
  14621. }
  14622. }
  14623. }
  14624. // actively set format to nothing, to allow this to be called more than once
  14625. // and possibly fail the 2nd time
  14626. this._textureFormatInUse = null;
  14627. return null;
  14628. };
  14629. /** @hidden */
  14630. Engine.prototype._createTexture = function () {
  14631. var texture = this._gl.createTexture();
  14632. if (!texture) {
  14633. throw new Error("Unable to create texture");
  14634. }
  14635. return texture;
  14636. };
  14637. /**
  14638. * Usually called from BABYLON.Texture.ts.
  14639. * Passed information to create a WebGLTexture
  14640. * @param urlArg defines a value which contains one of the following:
  14641. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14642. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14643. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14644. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14645. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14646. * @param scene needed for loading to the correct scene
  14647. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14648. * @param onLoad optional callback to be called upon successful completion
  14649. * @param onError optional callback to be called upon failure
  14650. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14651. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14652. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14653. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14654. */
  14655. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14656. var _this = this;
  14657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14658. if (onLoad === void 0) { onLoad = null; }
  14659. if (onError === void 0) { onError = null; }
  14660. if (buffer === void 0) { buffer = null; }
  14661. if (fallback === void 0) { fallback = null; }
  14662. if (format === void 0) { format = null; }
  14663. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14664. var fromData = url.substr(0, 5) === "data:";
  14665. var fromBlob = url.substr(0, 5) === "blob:";
  14666. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14667. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14668. // establish the file extension, if possible
  14669. var lastDot = url.lastIndexOf('.');
  14670. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14671. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14672. var isTGA = (extension.indexOf(".tga") === 0);
  14673. // determine if a ktx file should be substituted
  14674. var isKTX = false;
  14675. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14676. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14677. isKTX = true;
  14678. }
  14679. if (scene) {
  14680. scene._addPendingData(texture);
  14681. }
  14682. texture.url = url;
  14683. texture.generateMipMaps = !noMipmap;
  14684. texture.samplingMode = samplingMode;
  14685. texture.invertY = invertY;
  14686. if (!this._doNotHandleContextLost) {
  14687. // Keep a link to the buffer only if we plan to handle context lost
  14688. texture._buffer = buffer;
  14689. }
  14690. var onLoadObserver = null;
  14691. if (onLoad && !fallback) {
  14692. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14693. }
  14694. if (!fallback)
  14695. this._internalTexturesCache.push(texture);
  14696. var onerror = function (message, exception) {
  14697. if (scene) {
  14698. scene._removePendingData(texture);
  14699. }
  14700. if (onLoadObserver && !isKTX) {
  14701. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14702. texture.onLoadedObservable.remove(onLoadObserver);
  14703. }
  14704. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14705. if (isKTX) {
  14706. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14707. }
  14708. else if (BABYLON.Tools.UseFallbackTexture) {
  14709. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14710. }
  14711. if (onError) {
  14712. onError(message || "Unknown error", exception);
  14713. }
  14714. };
  14715. var callback = null;
  14716. // processing for non-image formats
  14717. if (isKTX || isTGA || isDDS) {
  14718. if (isKTX) {
  14719. callback = function (data) {
  14720. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14721. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14722. ktx.uploadLevels(_this._gl, !noMipmap);
  14723. return false;
  14724. }, samplingMode);
  14725. };
  14726. }
  14727. else if (isTGA) {
  14728. callback = function (arrayBuffer) {
  14729. var data = new Uint8Array(arrayBuffer);
  14730. var header = BABYLON.TGATools.GetTGAHeader(data);
  14731. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14732. BABYLON.TGATools.UploadContent(_this._gl, data);
  14733. return false;
  14734. }, samplingMode);
  14735. };
  14736. }
  14737. else if (isDDS) {
  14738. callback = function (data) {
  14739. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14740. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14741. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14742. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14743. return false;
  14744. }, samplingMode);
  14745. };
  14746. }
  14747. if (!buffer) {
  14748. this._loadFile(url, function (data) {
  14749. if (callback) {
  14750. callback(data);
  14751. }
  14752. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14753. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14754. });
  14755. }
  14756. else {
  14757. if (callback) {
  14758. callback(buffer);
  14759. }
  14760. }
  14761. // image format processing
  14762. }
  14763. else {
  14764. var onload = function (img) {
  14765. if (fromBlob && !_this._doNotHandleContextLost) {
  14766. // We need to store the image if we need to rebuild the texture
  14767. // in case of a webgl context lost
  14768. texture._buffer = img;
  14769. }
  14770. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14771. var gl = _this._gl;
  14772. var isPot = (img.width === potWidth && img.height === potHeight);
  14773. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14774. if (isPot) {
  14775. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14776. return false;
  14777. }
  14778. var maxTextureSize = _this._caps.maxTextureSize;
  14779. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14780. _this._prepareWorkingCanvas();
  14781. if (!_this._workingCanvas || !_this._workingContext) {
  14782. return false;
  14783. }
  14784. _this._workingCanvas.width = potWidth;
  14785. _this._workingCanvas.height = potHeight;
  14786. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14787. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14788. texture.width = potWidth;
  14789. texture.height = potHeight;
  14790. return false;
  14791. }
  14792. else {
  14793. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14794. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14795. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14796. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14797. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14798. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14801. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14802. _this._releaseTexture(source_1);
  14803. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14804. continuationCallback();
  14805. });
  14806. }
  14807. return true;
  14808. }, samplingMode);
  14809. };
  14810. if (!fromData || isBase64) {
  14811. if (buffer instanceof HTMLImageElement) {
  14812. onload(buffer);
  14813. }
  14814. else {
  14815. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14816. }
  14817. }
  14818. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14819. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14820. }
  14821. else {
  14822. onload(buffer);
  14823. }
  14824. }
  14825. return texture;
  14826. };
  14827. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14828. var _this = this;
  14829. var rtt = this.createRenderTargetTexture({
  14830. width: destination.width,
  14831. height: destination.height,
  14832. }, {
  14833. generateMipMaps: false,
  14834. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14835. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14836. generateDepthBuffer: false,
  14837. generateStencilBuffer: false
  14838. });
  14839. if (!this._rescalePostProcess) {
  14840. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14841. }
  14842. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14843. _this._rescalePostProcess.onApply = function (effect) {
  14844. effect._bindTexture("textureSampler", source);
  14845. };
  14846. var hostingScene = scene;
  14847. if (!hostingScene) {
  14848. hostingScene = _this.scenes[_this.scenes.length - 1];
  14849. }
  14850. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14851. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14852. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14853. _this.unBindFramebuffer(rtt);
  14854. _this._releaseTexture(rtt);
  14855. if (onComplete) {
  14856. onComplete();
  14857. }
  14858. });
  14859. };
  14860. /**
  14861. * Update a raw texture
  14862. * @param texture defines the texture to update
  14863. * @param data defines the data to store in the texture
  14864. * @param format defines the format of the data
  14865. * @param invertY defines if data must be stored with Y axis inverted
  14866. * @param compression defines the compression used (null by default)
  14867. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14868. */
  14869. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14870. if (compression === void 0) { compression = null; }
  14871. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14872. if (!texture) {
  14873. return;
  14874. }
  14875. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14876. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14877. // babylon's internalFormat but gl's texImage2D format
  14878. var internalFormat = this._getInternalFormat(format);
  14879. var textureType = this._getWebGLTextureType(type);
  14880. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14881. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14882. if (!this._doNotHandleContextLost) {
  14883. texture._bufferView = data;
  14884. texture.format = format;
  14885. texture.type = type;
  14886. texture.invertY = invertY;
  14887. texture._compression = compression;
  14888. }
  14889. if (texture.width % 4 !== 0) {
  14890. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14891. }
  14892. if (compression && data) {
  14893. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14894. }
  14895. else {
  14896. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14897. }
  14898. if (texture.generateMipMaps) {
  14899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14900. }
  14901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14902. // this.resetTextureCache();
  14903. texture.isReady = true;
  14904. };
  14905. /**
  14906. * Creates a raw texture
  14907. * @param data defines the data to store in the texture
  14908. * @param width defines the width of the texture
  14909. * @param height defines the height of the texture
  14910. * @param format defines the format of the data
  14911. * @param generateMipMaps defines if the engine should generate the mip levels
  14912. * @param invertY defines if data must be stored with Y axis inverted
  14913. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14914. * @param compression defines the compression used (null by default)
  14915. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14916. * @returns the raw texture inside an InternalTexture
  14917. */
  14918. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14919. if (compression === void 0) { compression = null; }
  14920. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14921. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14922. texture.baseWidth = width;
  14923. texture.baseHeight = height;
  14924. texture.width = width;
  14925. texture.height = height;
  14926. texture.format = format;
  14927. texture.generateMipMaps = generateMipMaps;
  14928. texture.samplingMode = samplingMode;
  14929. texture.invertY = invertY;
  14930. texture._compression = compression;
  14931. texture.type = type;
  14932. if (!this._doNotHandleContextLost) {
  14933. texture._bufferView = data;
  14934. }
  14935. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14936. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14937. // Filters
  14938. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14939. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14940. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14941. if (generateMipMaps) {
  14942. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14943. }
  14944. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14945. this._internalTexturesCache.push(texture);
  14946. return texture;
  14947. };
  14948. /** @hidden */
  14949. Engine.prototype._unpackFlipY = function (value) {
  14950. if (this._unpackFlipYCached !== value) {
  14951. this._unpackFlipYCached = value;
  14952. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14953. }
  14954. };
  14955. /**
  14956. * Creates a dynamic texture
  14957. * @param width defines the width of the texture
  14958. * @param height defines the height of the texture
  14959. * @param generateMipMaps defines if the engine should generate the mip levels
  14960. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14961. * @returns the dynamic texture inside an InternalTexture
  14962. */
  14963. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14964. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14965. texture.baseWidth = width;
  14966. texture.baseHeight = height;
  14967. if (generateMipMaps) {
  14968. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14969. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14970. }
  14971. // this.resetTextureCache();
  14972. texture.width = width;
  14973. texture.height = height;
  14974. texture.isReady = false;
  14975. texture.generateMipMaps = generateMipMaps;
  14976. texture.samplingMode = samplingMode;
  14977. this.updateTextureSamplingMode(samplingMode, texture);
  14978. this._internalTexturesCache.push(texture);
  14979. return texture;
  14980. };
  14981. /**
  14982. * Update the sampling mode of a given texture
  14983. * @param samplingMode defines the required sampling mode
  14984. * @param texture defines the texture to update
  14985. */
  14986. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14987. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14988. if (texture.isCube) {
  14989. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14990. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14991. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14992. }
  14993. else if (texture.is3D) {
  14994. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14995. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14996. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14997. }
  14998. else {
  14999. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15000. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15001. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15002. }
  15003. texture.samplingMode = samplingMode;
  15004. };
  15005. /**
  15006. * Update the content of a dynamic texture
  15007. * @param texture defines the texture to update
  15008. * @param canvas defines the canvas containing the source
  15009. * @param invertY defines if data must be stored with Y axis inverted
  15010. * @param premulAlpha defines if alpha is stored as premultiplied
  15011. * @param format defines the format of the data
  15012. */
  15013. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15014. if (premulAlpha === void 0) { premulAlpha = false; }
  15015. if (!texture) {
  15016. return;
  15017. }
  15018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15019. this._unpackFlipY(invertY);
  15020. if (premulAlpha) {
  15021. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15022. }
  15023. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15024. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15025. if (texture.generateMipMaps) {
  15026. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15027. }
  15028. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15029. if (premulAlpha) {
  15030. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15031. }
  15032. texture.isReady = true;
  15033. };
  15034. /**
  15035. * Update a video texture
  15036. * @param texture defines the texture to update
  15037. * @param video defines the video element to use
  15038. * @param invertY defines if data must be stored with Y axis inverted
  15039. */
  15040. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15041. if (!texture || texture._isDisabled) {
  15042. return;
  15043. }
  15044. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15045. this._unpackFlipY(!invertY); // Video are upside down by default
  15046. try {
  15047. // Testing video texture support
  15048. if (this._videoTextureSupported === undefined) {
  15049. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15050. if (this._gl.getError() !== 0) {
  15051. this._videoTextureSupported = false;
  15052. }
  15053. else {
  15054. this._videoTextureSupported = true;
  15055. }
  15056. }
  15057. // Copy video through the current working canvas if video texture is not supported
  15058. if (!this._videoTextureSupported) {
  15059. if (!texture._workingCanvas) {
  15060. texture._workingCanvas = document.createElement("canvas");
  15061. var context = texture._workingCanvas.getContext("2d");
  15062. if (!context) {
  15063. throw new Error("Unable to get 2d context");
  15064. }
  15065. texture._workingContext = context;
  15066. texture._workingCanvas.width = texture.width;
  15067. texture._workingCanvas.height = texture.height;
  15068. }
  15069. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15070. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15071. }
  15072. else {
  15073. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15074. }
  15075. if (texture.generateMipMaps) {
  15076. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15077. }
  15078. if (!wasPreviouslyBound) {
  15079. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15080. }
  15081. // this.resetTextureCache();
  15082. texture.isReady = true;
  15083. }
  15084. catch (ex) {
  15085. // Something unexpected
  15086. // Let's disable the texture
  15087. texture._isDisabled = true;
  15088. }
  15089. };
  15090. /**
  15091. * Updates a depth texture Comparison Mode and Function.
  15092. * If the comparison Function is equal to 0, the mode will be set to none.
  15093. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15094. * @param texture The texture to set the comparison function for
  15095. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15096. */
  15097. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15098. if (this.webGLVersion === 1) {
  15099. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15100. return;
  15101. }
  15102. var gl = this._gl;
  15103. if (texture.isCube) {
  15104. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15105. if (comparisonFunction === 0) {
  15106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15108. }
  15109. else {
  15110. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15112. }
  15113. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15114. }
  15115. else {
  15116. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15117. if (comparisonFunction === 0) {
  15118. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15119. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15120. }
  15121. else {
  15122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15124. }
  15125. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15126. }
  15127. texture._comparisonFunction = comparisonFunction;
  15128. };
  15129. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15130. var width = size.width || size;
  15131. var height = size.height || size;
  15132. internalTexture.baseWidth = width;
  15133. internalTexture.baseHeight = height;
  15134. internalTexture.width = width;
  15135. internalTexture.height = height;
  15136. internalTexture.isReady = true;
  15137. internalTexture.samples = 1;
  15138. internalTexture.generateMipMaps = false;
  15139. internalTexture._generateDepthBuffer = true;
  15140. internalTexture._generateStencilBuffer = generateStencil;
  15141. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15142. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15143. internalTexture._comparisonFunction = comparisonFunction;
  15144. var gl = this._gl;
  15145. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15146. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15147. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15148. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15149. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15150. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15151. if (comparisonFunction === 0) {
  15152. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15153. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15154. }
  15155. else {
  15156. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15157. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15158. }
  15159. };
  15160. /**
  15161. * Creates a depth stencil texture.
  15162. * This is only available in WebGL 2 or with the depth texture extension available.
  15163. * @param size The size of face edge in the texture.
  15164. * @param options The options defining the texture.
  15165. * @returns The texture
  15166. */
  15167. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15168. if (options.isCube) {
  15169. var width = size.width || size;
  15170. return this._createDepthStencilCubeTexture(width, options);
  15171. }
  15172. else {
  15173. return this._createDepthStencilTexture(size, options);
  15174. }
  15175. };
  15176. /**
  15177. * Creates a depth stencil texture.
  15178. * This is only available in WebGL 2 or with the depth texture extension available.
  15179. * @param size The size of face edge in the texture.
  15180. * @param options The options defining the texture.
  15181. * @returns The texture
  15182. */
  15183. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15184. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15185. if (!this._caps.depthTextureExtension) {
  15186. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15187. return internalTexture;
  15188. }
  15189. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15190. var gl = this._gl;
  15191. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15192. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15193. if (this.webGLVersion > 1) {
  15194. if (internalOptions.generateStencil) {
  15195. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15196. }
  15197. else {
  15198. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15199. }
  15200. }
  15201. else {
  15202. if (internalOptions.generateStencil) {
  15203. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15204. }
  15205. else {
  15206. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15207. }
  15208. }
  15209. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15210. return internalTexture;
  15211. };
  15212. /**
  15213. * Creates a depth stencil cube texture.
  15214. * This is only available in WebGL 2.
  15215. * @param size The size of face edge in the cube texture.
  15216. * @param options The options defining the cube texture.
  15217. * @returns The cube texture
  15218. */
  15219. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15220. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15221. internalTexture.isCube = true;
  15222. if (this.webGLVersion === 1) {
  15223. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15224. return internalTexture;
  15225. }
  15226. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15227. var gl = this._gl;
  15228. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15229. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15230. // Create the depth/stencil buffer
  15231. for (var face = 0; face < 6; face++) {
  15232. if (internalOptions.generateStencil) {
  15233. 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);
  15234. }
  15235. else {
  15236. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15237. }
  15238. }
  15239. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15240. return internalTexture;
  15241. };
  15242. /**
  15243. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15244. * @param renderTarget The render target to set the frame buffer for
  15245. */
  15246. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15247. // Create the framebuffer
  15248. var internalTexture = renderTarget.getInternalTexture();
  15249. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15250. return;
  15251. }
  15252. var gl = this._gl;
  15253. var depthStencilTexture = renderTarget.depthStencilTexture;
  15254. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15255. if (depthStencilTexture.isCube) {
  15256. if (depthStencilTexture._generateStencilBuffer) {
  15257. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15258. }
  15259. else {
  15260. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15261. }
  15262. }
  15263. else {
  15264. if (depthStencilTexture._generateStencilBuffer) {
  15265. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15266. }
  15267. else {
  15268. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15269. }
  15270. }
  15271. this.bindUnboundFramebuffer(null);
  15272. };
  15273. /**
  15274. * Creates a new render target texture
  15275. * @param size defines the size of the texture
  15276. * @param options defines the options used to create the texture
  15277. * @returns a new render target texture stored in an InternalTexture
  15278. */
  15279. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15280. var fullOptions = new RenderTargetCreationOptions();
  15281. if (options !== undefined && typeof options === "object") {
  15282. fullOptions.generateMipMaps = options.generateMipMaps;
  15283. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15284. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15285. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15286. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15287. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15288. }
  15289. else {
  15290. fullOptions.generateMipMaps = options;
  15291. fullOptions.generateDepthBuffer = true;
  15292. fullOptions.generateStencilBuffer = false;
  15293. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15294. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15295. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15296. }
  15297. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15298. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15299. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15300. }
  15301. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15302. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15303. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15304. }
  15305. var gl = this._gl;
  15306. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15307. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15308. var width = size.width || size;
  15309. var height = size.height || size;
  15310. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15311. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15312. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15313. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15314. }
  15315. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15316. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15317. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15319. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15320. // Create the framebuffer
  15321. var currentFrameBuffer = this._currentFramebuffer;
  15322. var framebuffer = gl.createFramebuffer();
  15323. this.bindUnboundFramebuffer(framebuffer);
  15324. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15325. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15326. if (fullOptions.generateMipMaps) {
  15327. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15328. }
  15329. // Unbind
  15330. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15332. this.bindUnboundFramebuffer(currentFrameBuffer);
  15333. texture._framebuffer = framebuffer;
  15334. texture.baseWidth = width;
  15335. texture.baseHeight = height;
  15336. texture.width = width;
  15337. texture.height = height;
  15338. texture.isReady = true;
  15339. texture.samples = 1;
  15340. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15341. texture.samplingMode = fullOptions.samplingMode;
  15342. texture.type = fullOptions.type;
  15343. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15344. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15345. // this.resetTextureCache();
  15346. this._internalTexturesCache.push(texture);
  15347. return texture;
  15348. };
  15349. /**
  15350. * Create a multi render target texture
  15351. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15352. * @param size defines the size of the texture
  15353. * @param options defines the creation options
  15354. * @returns the cube texture as an InternalTexture
  15355. */
  15356. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15357. var generateMipMaps = false;
  15358. var generateDepthBuffer = true;
  15359. var generateStencilBuffer = false;
  15360. var generateDepthTexture = false;
  15361. var textureCount = 1;
  15362. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15363. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15364. var types = new Array();
  15365. var samplingModes = new Array();
  15366. if (options !== undefined) {
  15367. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15368. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15369. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15370. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15371. textureCount = options.textureCount || 1;
  15372. if (options.types) {
  15373. types = options.types;
  15374. }
  15375. if (options.samplingModes) {
  15376. samplingModes = options.samplingModes;
  15377. }
  15378. }
  15379. var gl = this._gl;
  15380. // Create the framebuffer
  15381. var framebuffer = gl.createFramebuffer();
  15382. this.bindUnboundFramebuffer(framebuffer);
  15383. var width = size.width || size;
  15384. var height = size.height || size;
  15385. var textures = [];
  15386. var attachments = [];
  15387. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15388. for (var i = 0; i < textureCount; i++) {
  15389. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15390. var type = types[i] || defaultType;
  15391. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15392. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15393. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15394. }
  15395. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15396. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15397. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15398. }
  15399. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15400. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15401. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15402. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15403. }
  15404. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15405. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15406. textures.push(texture);
  15407. attachments.push(attachment);
  15408. gl.activeTexture(gl["TEXTURE" + i]);
  15409. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15413. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15414. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15415. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15416. if (generateMipMaps) {
  15417. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15418. }
  15419. // Unbind
  15420. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15421. texture._framebuffer = framebuffer;
  15422. texture._depthStencilBuffer = depthStencilBuffer;
  15423. texture.baseWidth = width;
  15424. texture.baseHeight = height;
  15425. texture.width = width;
  15426. texture.height = height;
  15427. texture.isReady = true;
  15428. texture.samples = 1;
  15429. texture.generateMipMaps = generateMipMaps;
  15430. texture.samplingMode = samplingMode;
  15431. texture.type = type;
  15432. texture._generateDepthBuffer = generateDepthBuffer;
  15433. texture._generateStencilBuffer = generateStencilBuffer;
  15434. texture._attachments = attachments;
  15435. this._internalTexturesCache.push(texture);
  15436. }
  15437. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15438. // Depth texture
  15439. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15440. gl.activeTexture(gl.TEXTURE0);
  15441. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15442. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15443. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15444. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15446. 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);
  15447. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15448. depthTexture._framebuffer = framebuffer;
  15449. depthTexture.baseWidth = width;
  15450. depthTexture.baseHeight = height;
  15451. depthTexture.width = width;
  15452. depthTexture.height = height;
  15453. depthTexture.isReady = true;
  15454. depthTexture.samples = 1;
  15455. depthTexture.generateMipMaps = generateMipMaps;
  15456. depthTexture.samplingMode = gl.NEAREST;
  15457. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15458. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15459. textures.push(depthTexture);
  15460. this._internalTexturesCache.push(depthTexture);
  15461. }
  15462. gl.drawBuffers(attachments);
  15463. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15464. this.bindUnboundFramebuffer(null);
  15465. this.resetTextureCache();
  15466. return textures;
  15467. };
  15468. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15469. if (samples === void 0) { samples = 1; }
  15470. var depthStencilBuffer = null;
  15471. var gl = this._gl;
  15472. // Create the depth/stencil buffer
  15473. if (generateStencilBuffer) {
  15474. depthStencilBuffer = gl.createRenderbuffer();
  15475. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15476. if (samples > 1) {
  15477. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15478. }
  15479. else {
  15480. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15481. }
  15482. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15483. }
  15484. else if (generateDepthBuffer) {
  15485. depthStencilBuffer = gl.createRenderbuffer();
  15486. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15487. if (samples > 1) {
  15488. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15489. }
  15490. else {
  15491. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15492. }
  15493. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15494. }
  15495. return depthStencilBuffer;
  15496. };
  15497. /**
  15498. * Updates the sample count of a render target texture
  15499. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15500. * @param texture defines the texture to update
  15501. * @param samples defines the sample count to set
  15502. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15503. */
  15504. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15505. if (this.webGLVersion < 2 || !texture) {
  15506. return 1;
  15507. }
  15508. if (texture.samples === samples) {
  15509. return samples;
  15510. }
  15511. var gl = this._gl;
  15512. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15513. // Dispose previous render buffers
  15514. if (texture._depthStencilBuffer) {
  15515. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15516. texture._depthStencilBuffer = null;
  15517. }
  15518. if (texture._MSAAFramebuffer) {
  15519. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15520. texture._MSAAFramebuffer = null;
  15521. }
  15522. if (texture._MSAARenderBuffer) {
  15523. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15524. texture._MSAARenderBuffer = null;
  15525. }
  15526. if (samples > 1) {
  15527. var framebuffer = gl.createFramebuffer();
  15528. if (!framebuffer) {
  15529. throw new Error("Unable to create multi sampled framebuffer");
  15530. }
  15531. texture._MSAAFramebuffer = framebuffer;
  15532. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15533. var colorRenderbuffer = gl.createRenderbuffer();
  15534. if (!colorRenderbuffer) {
  15535. throw new Error("Unable to create multi sampled framebuffer");
  15536. }
  15537. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15538. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15539. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15540. texture._MSAARenderBuffer = colorRenderbuffer;
  15541. }
  15542. else {
  15543. this.bindUnboundFramebuffer(texture._framebuffer);
  15544. }
  15545. texture.samples = samples;
  15546. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15547. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15548. this.bindUnboundFramebuffer(null);
  15549. return samples;
  15550. };
  15551. /**
  15552. * Update the sample count for a given multiple render target texture
  15553. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15554. * @param textures defines the textures to update
  15555. * @param samples defines the sample count to set
  15556. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15557. */
  15558. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15559. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15560. return 1;
  15561. }
  15562. if (textures[0].samples === samples) {
  15563. return samples;
  15564. }
  15565. var gl = this._gl;
  15566. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15567. // Dispose previous render buffers
  15568. if (textures[0]._depthStencilBuffer) {
  15569. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15570. textures[0]._depthStencilBuffer = null;
  15571. }
  15572. if (textures[0]._MSAAFramebuffer) {
  15573. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15574. textures[0]._MSAAFramebuffer = null;
  15575. }
  15576. for (var i = 0; i < textures.length; i++) {
  15577. if (textures[i]._MSAARenderBuffer) {
  15578. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15579. textures[i]._MSAARenderBuffer = null;
  15580. }
  15581. }
  15582. if (samples > 1) {
  15583. var framebuffer = gl.createFramebuffer();
  15584. if (!framebuffer) {
  15585. throw new Error("Unable to create multi sampled framebuffer");
  15586. }
  15587. this.bindUnboundFramebuffer(framebuffer);
  15588. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15589. var attachments = [];
  15590. for (var i = 0; i < textures.length; i++) {
  15591. var texture = textures[i];
  15592. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15593. var colorRenderbuffer = gl.createRenderbuffer();
  15594. if (!colorRenderbuffer) {
  15595. throw new Error("Unable to create multi sampled framebuffer");
  15596. }
  15597. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15598. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15599. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15600. texture._MSAAFramebuffer = framebuffer;
  15601. texture._MSAARenderBuffer = colorRenderbuffer;
  15602. texture.samples = samples;
  15603. texture._depthStencilBuffer = depthStencilBuffer;
  15604. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15605. attachments.push(attachment);
  15606. }
  15607. gl.drawBuffers(attachments);
  15608. }
  15609. else {
  15610. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15611. }
  15612. this.bindUnboundFramebuffer(null);
  15613. return samples;
  15614. };
  15615. /** @hidden */
  15616. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15617. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15618. };
  15619. /** @hidden */
  15620. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15621. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15622. };
  15623. /** @hidden */
  15624. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15625. var gl = this._gl;
  15626. var textureType = this._getWebGLTextureType(texture.type);
  15627. var format = this._getInternalFormat(texture.format);
  15628. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15629. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15630. this._bindTextureDirectly(bindTarget, texture, true);
  15631. this._unpackFlipY(texture.invertY);
  15632. var target = gl.TEXTURE_2D;
  15633. if (texture.isCube) {
  15634. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15635. }
  15636. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15637. this._bindTextureDirectly(bindTarget, null, true);
  15638. };
  15639. /**
  15640. * Creates a new render target cube texture
  15641. * @param size defines the size of the texture
  15642. * @param options defines the options used to create the texture
  15643. * @returns a new render target cube texture stored in an InternalTexture
  15644. */
  15645. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15646. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15647. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15648. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15649. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15650. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15651. }
  15652. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15653. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15654. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15655. }
  15656. var gl = this._gl;
  15657. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15658. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15659. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15660. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15661. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15662. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15663. }
  15664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15668. for (var face = 0; face < 6; face++) {
  15669. 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);
  15670. }
  15671. // Create the framebuffer
  15672. var framebuffer = gl.createFramebuffer();
  15673. this.bindUnboundFramebuffer(framebuffer);
  15674. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15675. // MipMaps
  15676. if (fullOptions.generateMipMaps) {
  15677. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15678. }
  15679. // Unbind
  15680. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15681. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15682. this.bindUnboundFramebuffer(null);
  15683. texture._framebuffer = framebuffer;
  15684. texture.width = size;
  15685. texture.height = size;
  15686. texture.isReady = true;
  15687. texture.isCube = true;
  15688. texture.samples = 1;
  15689. texture.generateMipMaps = fullOptions.generateMipMaps;
  15690. texture.samplingMode = fullOptions.samplingMode;
  15691. texture.type = fullOptions.type;
  15692. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15693. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15694. this._internalTexturesCache.push(texture);
  15695. return texture;
  15696. };
  15697. /**
  15698. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15699. * @param rootUrl defines the url where the file to load is located
  15700. * @param scene defines the current scene
  15701. * @param lodScale defines scale to apply to the mip map selection
  15702. * @param lodOffset defines offset to apply to the mip map selection
  15703. * @param onLoad defines an optional callback raised when the texture is loaded
  15704. * @param onError defines an optional callback raised if there is an issue to load the texture
  15705. * @param format defines the format of the data
  15706. * @param forcedExtension defines the extension to use to pick the right loader
  15707. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15708. * @returns the cube texture as an InternalTexture
  15709. */
  15710. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15711. var _this = this;
  15712. if (onLoad === void 0) { onLoad = null; }
  15713. if (onError === void 0) { onError = null; }
  15714. if (forcedExtension === void 0) { forcedExtension = null; }
  15715. if (createPolynomials === void 0) { createPolynomials = true; }
  15716. var callback = function (loadData) {
  15717. if (!loadData) {
  15718. if (onLoad) {
  15719. onLoad(null);
  15720. }
  15721. return;
  15722. }
  15723. var texture = loadData.texture;
  15724. if (!createPolynomials) {
  15725. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15726. }
  15727. else if (loadData.info.sphericalPolynomial) {
  15728. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15729. }
  15730. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15731. if (_this._caps.textureLOD) {
  15732. // Do not add extra process if texture lod is supported.
  15733. if (onLoad) {
  15734. onLoad(texture);
  15735. }
  15736. return;
  15737. }
  15738. var mipSlices = 3;
  15739. var gl = _this._gl;
  15740. var width = loadData.width;
  15741. if (!width) {
  15742. return;
  15743. }
  15744. var textures = [];
  15745. for (var i = 0; i < mipSlices; i++) {
  15746. //compute LOD from even spacing in smoothness (matching shader calculation)
  15747. var smoothness = i / (mipSlices - 1);
  15748. var roughness = 1 - smoothness;
  15749. var minLODIndex = lodOffset; // roughness = 0
  15750. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15751. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15752. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15753. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15754. glTextureFromLod.isCube = true;
  15755. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15756. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15760. if (loadData.isDDS) {
  15761. var info = loadData.info;
  15762. var data = loadData.data;
  15763. _this._unpackFlipY(info.isCompressed);
  15764. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15765. }
  15766. else {
  15767. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15768. }
  15769. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15770. // Wrap in a base texture for easy binding.
  15771. var lodTexture = new BABYLON.BaseTexture(scene);
  15772. lodTexture.isCube = true;
  15773. lodTexture._texture = glTextureFromLod;
  15774. glTextureFromLod.isReady = true;
  15775. textures.push(lodTexture);
  15776. }
  15777. texture._lodTextureHigh = textures[2];
  15778. texture._lodTextureMid = textures[1];
  15779. texture._lodTextureLow = textures[0];
  15780. if (onLoad) {
  15781. onLoad(texture);
  15782. }
  15783. };
  15784. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15785. };
  15786. /**
  15787. * Creates a cube texture
  15788. * @param rootUrl defines the url where the files to load is located
  15789. * @param scene defines the current scene
  15790. * @param files defines the list of files to load (1 per face)
  15791. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15792. * @param onLoad defines an optional callback raised when the texture is loaded
  15793. * @param onError defines an optional callback raised if there is an issue to load the texture
  15794. * @param format defines the format of the data
  15795. * @param forcedExtension defines the extension to use to pick the right loader
  15796. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15797. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15798. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15799. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15800. * @returns the cube texture as an InternalTexture
  15801. */
  15802. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15803. var _this = this;
  15804. if (onLoad === void 0) { onLoad = null; }
  15805. if (onError === void 0) { onError = null; }
  15806. if (forcedExtension === void 0) { forcedExtension = null; }
  15807. if (createPolynomials === void 0) { createPolynomials = false; }
  15808. if (lodScale === void 0) { lodScale = 0; }
  15809. if (lodOffset === void 0) { lodOffset = 0; }
  15810. if (fallback === void 0) { fallback = null; }
  15811. var gl = this._gl;
  15812. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15813. texture.isCube = true;
  15814. texture.url = rootUrl;
  15815. texture.generateMipMaps = !noMipmap;
  15816. texture._lodGenerationScale = lodScale;
  15817. texture._lodGenerationOffset = lodOffset;
  15818. if (!this._doNotHandleContextLost) {
  15819. texture._extension = forcedExtension;
  15820. texture._files = files;
  15821. }
  15822. var isKTX = false;
  15823. var isDDS = false;
  15824. var isEnv = false;
  15825. var lastDot = rootUrl.lastIndexOf('.');
  15826. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15827. if (this._textureFormatInUse && !fallback) {
  15828. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15829. isKTX = true;
  15830. }
  15831. else {
  15832. isDDS = (extension === ".dds");
  15833. isEnv = (extension === ".env");
  15834. }
  15835. var onerror = function (request, exception) {
  15836. if (isKTX) {
  15837. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15838. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15839. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15840. }
  15841. if (onError && request) {
  15842. onError(request.status + " " + request.statusText, exception);
  15843. }
  15844. };
  15845. if (isKTX) {
  15846. this._loadFile(rootUrl, function (data) {
  15847. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15848. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15849. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15850. _this._unpackFlipY(true);
  15851. ktx.uploadLevels(_this._gl, !noMipmap);
  15852. _this.setCubeMapTextureParams(gl, loadMipmap);
  15853. texture.width = ktx.pixelWidth;
  15854. texture.height = ktx.pixelHeight;
  15855. texture.isReady = true;
  15856. }, undefined, undefined, true, onerror);
  15857. }
  15858. else if (isEnv) {
  15859. this._loadFile(rootUrl, function (data) {
  15860. data = data;
  15861. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15862. if (info) {
  15863. texture.width = info.width;
  15864. texture.height = info.width;
  15865. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  15866. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  15867. texture.isReady = true;
  15868. if (onLoad) {
  15869. onLoad();
  15870. }
  15871. });
  15872. }
  15873. else if (onError) {
  15874. onError("Can not parse the environment file", null);
  15875. }
  15876. }, undefined, undefined, true, onerror);
  15877. }
  15878. else if (isDDS) {
  15879. if (files && files.length === 6) {
  15880. this._cascadeLoadFiles(scene, function (imgs) {
  15881. var info;
  15882. var loadMipmap = false;
  15883. var width = 0;
  15884. for (var index = 0; index < imgs.length; index++) {
  15885. var data = imgs[index];
  15886. info = BABYLON.DDSTools.GetDDSInfo(data);
  15887. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15888. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15889. _this._unpackFlipY(info.isCompressed);
  15890. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15891. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15892. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15893. }
  15894. texture.width = info.width;
  15895. texture.height = info.height;
  15896. texture.type = info.textureType;
  15897. width = info.width;
  15898. }
  15899. _this.setCubeMapTextureParams(gl, loadMipmap);
  15900. texture.isReady = true;
  15901. if (onLoad) {
  15902. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15903. }
  15904. }, files, onError);
  15905. }
  15906. else {
  15907. this._loadFile(rootUrl, function (data) {
  15908. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15909. if (createPolynomials) {
  15910. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15911. }
  15912. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15913. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15914. _this._unpackFlipY(info.isCompressed);
  15915. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15916. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15917. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15918. }
  15919. _this.setCubeMapTextureParams(gl, loadMipmap);
  15920. texture.width = info.width;
  15921. texture.height = info.height;
  15922. texture.isReady = true;
  15923. texture.type = info.textureType;
  15924. if (onLoad) {
  15925. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15926. }
  15927. }, undefined, undefined, true, onerror);
  15928. }
  15929. }
  15930. else {
  15931. if (!files) {
  15932. throw new Error("Cannot load cubemap because files were not defined");
  15933. }
  15934. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15935. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15936. var height = width;
  15937. _this._prepareWorkingCanvas();
  15938. if (!_this._workingCanvas || !_this._workingContext) {
  15939. return;
  15940. }
  15941. _this._workingCanvas.width = width;
  15942. _this._workingCanvas.height = height;
  15943. var faces = [
  15944. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15945. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15946. ];
  15947. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15948. _this._unpackFlipY(false);
  15949. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15950. for (var index = 0; index < faces.length; index++) {
  15951. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15952. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15953. }
  15954. if (!noMipmap) {
  15955. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15956. }
  15957. _this.setCubeMapTextureParams(gl, !noMipmap);
  15958. texture.width = width;
  15959. texture.height = height;
  15960. texture.isReady = true;
  15961. if (format) {
  15962. texture.format = format;
  15963. }
  15964. texture.onLoadedObservable.notifyObservers(texture);
  15965. texture.onLoadedObservable.clear();
  15966. if (onLoad) {
  15967. onLoad();
  15968. }
  15969. }, files, onError);
  15970. }
  15971. this._internalTexturesCache.push(texture);
  15972. return texture;
  15973. };
  15974. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15975. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15977. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15979. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15980. // this.resetTextureCache();
  15981. };
  15982. /**
  15983. * Update a raw cube texture
  15984. * @param texture defines the texture to udpdate
  15985. * @param data defines the data to store
  15986. * @param format defines the data format
  15987. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15988. * @param invertY defines if data must be stored with Y axis inverted
  15989. * @param compression defines the compression used (null by default)
  15990. * @param level defines which level of the texture to update
  15991. */
  15992. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15993. if (compression === void 0) { compression = null; }
  15994. if (level === void 0) { level = 0; }
  15995. texture._bufferViewArray = data;
  15996. texture.format = format;
  15997. texture.type = type;
  15998. texture.invertY = invertY;
  15999. texture._compression = compression;
  16000. var gl = this._gl;
  16001. var textureType = this._getWebGLTextureType(type);
  16002. var internalFormat = this._getInternalFormat(format);
  16003. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16004. var needConversion = false;
  16005. if (internalFormat === gl.RGB) {
  16006. internalFormat = gl.RGBA;
  16007. needConversion = true;
  16008. }
  16009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16010. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16011. if (texture.width % 4 !== 0) {
  16012. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16013. }
  16014. // Data are known to be in +X +Y +Z -X -Y -Z
  16015. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16016. var faceData = data[faceIndex];
  16017. if (compression) {
  16018. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16019. }
  16020. else {
  16021. if (needConversion) {
  16022. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16023. }
  16024. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16025. }
  16026. }
  16027. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16028. if (isPot && texture.generateMipMaps && level === 0) {
  16029. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16030. }
  16031. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16032. // this.resetTextureCache();
  16033. texture.isReady = true;
  16034. };
  16035. /**
  16036. * Creates a new raw cube texture
  16037. * @param data defines the array of data to use to create each face
  16038. * @param size defines the size of the textures
  16039. * @param format defines the format of the data
  16040. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16041. * @param generateMipMaps defines if the engine should generate the mip levels
  16042. * @param invertY defines if data must be stored with Y axis inverted
  16043. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16044. * @param compression defines the compression used (null by default)
  16045. * @returns the cube texture as an InternalTexture
  16046. */
  16047. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16048. if (compression === void 0) { compression = null; }
  16049. var gl = this._gl;
  16050. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16051. texture.isCube = true;
  16052. texture.generateMipMaps = generateMipMaps;
  16053. texture.format = format;
  16054. texture.type = type;
  16055. if (!this._doNotHandleContextLost) {
  16056. texture._bufferViewArray = data;
  16057. }
  16058. var textureType = this._getWebGLTextureType(type);
  16059. var internalFormat = this._getInternalFormat(format);
  16060. if (internalFormat === gl.RGB) {
  16061. internalFormat = gl.RGBA;
  16062. }
  16063. var width = size;
  16064. var height = width;
  16065. texture.width = width;
  16066. texture.height = height;
  16067. // Double check on POT to generate Mips.
  16068. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16069. if (!isPot) {
  16070. generateMipMaps = false;
  16071. }
  16072. // Upload data if needed. The texture won't be ready until then.
  16073. if (data) {
  16074. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16075. }
  16076. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16077. // Filters
  16078. if (data && generateMipMaps) {
  16079. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16080. }
  16081. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16082. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16083. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16084. }
  16085. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16087. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16088. }
  16089. else {
  16090. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16091. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16092. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16093. }
  16094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16097. return texture;
  16098. };
  16099. /**
  16100. * Creates a new raw cube texture from a specified url
  16101. * @param url defines the url where the data is located
  16102. * @param scene defines the current scene
  16103. * @param size defines the size of the textures
  16104. * @param format defines the format of the data
  16105. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16106. * @param noMipmap defines if the engine should avoid generating the mip levels
  16107. * @param callback defines a callback used to extract texture data from loaded data
  16108. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16109. * @param onLoad defines a callback called when texture is loaded
  16110. * @param onError defines a callback called if there is an error
  16111. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16112. * @param invertY defines if data must be stored with Y axis inverted
  16113. * @returns the cube texture as an InternalTexture
  16114. */
  16115. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16116. var _this = this;
  16117. if (onLoad === void 0) { onLoad = null; }
  16118. if (onError === void 0) { onError = null; }
  16119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16120. if (invertY === void 0) { invertY = false; }
  16121. var gl = this._gl;
  16122. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16123. scene._addPendingData(texture);
  16124. texture.url = url;
  16125. this._internalTexturesCache.push(texture);
  16126. var onerror = function (request, exception) {
  16127. scene._removePendingData(texture);
  16128. if (onError && request) {
  16129. onError(request.status + " " + request.statusText, exception);
  16130. }
  16131. };
  16132. var internalCallback = function (data) {
  16133. var width = texture.width;
  16134. var faceDataArrays = callback(data);
  16135. if (!faceDataArrays) {
  16136. return;
  16137. }
  16138. if (mipmapGenerator) {
  16139. var textureType = _this._getWebGLTextureType(type);
  16140. var internalFormat = _this._getInternalFormat(format);
  16141. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16142. var needConversion = false;
  16143. if (internalFormat === gl.RGB) {
  16144. internalFormat = gl.RGBA;
  16145. needConversion = true;
  16146. }
  16147. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16148. _this._unpackFlipY(false);
  16149. var mipData = mipmapGenerator(faceDataArrays);
  16150. for (var level = 0; level < mipData.length; level++) {
  16151. var mipSize = width >> level;
  16152. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16153. var mipFaceData = mipData[level][faceIndex];
  16154. if (needConversion) {
  16155. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16156. }
  16157. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16158. }
  16159. }
  16160. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16161. }
  16162. else {
  16163. texture.generateMipMaps = !noMipmap;
  16164. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16165. }
  16166. texture.isReady = true;
  16167. // this.resetTextureCache();
  16168. scene._removePendingData(texture);
  16169. if (onLoad) {
  16170. onLoad();
  16171. }
  16172. };
  16173. this._loadFile(url, function (data) {
  16174. internalCallback(data);
  16175. }, undefined, scene.database, true, onerror);
  16176. return texture;
  16177. };
  16178. ;
  16179. /**
  16180. * Update a raw 3D texture
  16181. * @param texture defines the texture to update
  16182. * @param data defines the data to store
  16183. * @param format defines the data format
  16184. * @param invertY defines if data must be stored with Y axis inverted
  16185. * @param compression defines the used compression (can be null)
  16186. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16187. */
  16188. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16189. if (compression === void 0) { compression = null; }
  16190. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16191. var internalType = this._getWebGLTextureType(textureType);
  16192. var internalFormat = this._getInternalFormat(format);
  16193. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16194. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16195. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16196. if (!this._doNotHandleContextLost) {
  16197. texture._bufferView = data;
  16198. texture.format = format;
  16199. texture.invertY = invertY;
  16200. texture._compression = compression;
  16201. }
  16202. if (texture.width % 4 !== 0) {
  16203. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16204. }
  16205. if (compression && data) {
  16206. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16207. }
  16208. else {
  16209. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16210. }
  16211. if (texture.generateMipMaps) {
  16212. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16213. }
  16214. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16215. // this.resetTextureCache();
  16216. texture.isReady = true;
  16217. };
  16218. /**
  16219. * Creates a new raw 3D texture
  16220. * @param data defines the data used to create the texture
  16221. * @param width defines the width of the texture
  16222. * @param height defines the height of the texture
  16223. * @param depth defines the depth of the texture
  16224. * @param format defines the format of the texture
  16225. * @param generateMipMaps defines if the engine must generate mip levels
  16226. * @param invertY defines if data must be stored with Y axis inverted
  16227. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16228. * @param compression defines the compressed used (can be null)
  16229. * @param textureType defines the compressed used (can be null)
  16230. * @returns a new raw 3D texture (stored in an InternalTexture)
  16231. */
  16232. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16233. if (compression === void 0) { compression = null; }
  16234. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16235. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16236. texture.baseWidth = width;
  16237. texture.baseHeight = height;
  16238. texture.baseDepth = depth;
  16239. texture.width = width;
  16240. texture.height = height;
  16241. texture.depth = depth;
  16242. texture.format = format;
  16243. texture.type = textureType;
  16244. texture.generateMipMaps = generateMipMaps;
  16245. texture.samplingMode = samplingMode;
  16246. texture.is3D = true;
  16247. if (!this._doNotHandleContextLost) {
  16248. texture._bufferView = data;
  16249. }
  16250. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16251. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16252. // Filters
  16253. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16254. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16255. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16256. if (generateMipMaps) {
  16257. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16258. }
  16259. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16260. this._internalTexturesCache.push(texture);
  16261. return texture;
  16262. };
  16263. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16264. var gl = this._gl;
  16265. if (!gl) {
  16266. return;
  16267. }
  16268. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16271. if (!noMipmap && !isCompressed) {
  16272. gl.generateMipmap(gl.TEXTURE_2D);
  16273. }
  16274. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16275. // this.resetTextureCache();
  16276. if (scene) {
  16277. scene._removePendingData(texture);
  16278. }
  16279. texture.onLoadedObservable.notifyObservers(texture);
  16280. texture.onLoadedObservable.clear();
  16281. };
  16282. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16283. var _this = this;
  16284. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16285. var maxTextureSize = this.getCaps().maxTextureSize;
  16286. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16287. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16288. var gl = this._gl;
  16289. if (!gl) {
  16290. return;
  16291. }
  16292. if (!texture._webGLTexture) {
  16293. // this.resetTextureCache();
  16294. if (scene) {
  16295. scene._removePendingData(texture);
  16296. }
  16297. return;
  16298. }
  16299. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16300. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16301. texture.baseWidth = width;
  16302. texture.baseHeight = height;
  16303. texture.width = potWidth;
  16304. texture.height = potHeight;
  16305. texture.isReady = true;
  16306. if (processFunction(potWidth, potHeight, function () {
  16307. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16308. })) {
  16309. // Returning as texture needs extra async steps
  16310. return;
  16311. }
  16312. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16313. };
  16314. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16315. // Create new RGBA data container.
  16316. var rgbaData;
  16317. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16318. rgbaData = new Float32Array(width * height * 4);
  16319. }
  16320. else {
  16321. rgbaData = new Uint32Array(width * height * 4);
  16322. }
  16323. // Convert each pixel.
  16324. for (var x = 0; x < width; x++) {
  16325. for (var y = 0; y < height; y++) {
  16326. var index = (y * width + x) * 3;
  16327. var newIndex = (y * width + x) * 4;
  16328. // Map Old Value to new value.
  16329. rgbaData[newIndex + 0] = rgbData[index + 0];
  16330. rgbaData[newIndex + 1] = rgbData[index + 1];
  16331. rgbaData[newIndex + 2] = rgbData[index + 2];
  16332. // Add fully opaque alpha channel.
  16333. rgbaData[newIndex + 3] = 1;
  16334. }
  16335. }
  16336. return rgbaData;
  16337. };
  16338. /** @hidden */
  16339. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16340. var gl = this._gl;
  16341. if (texture._framebuffer) {
  16342. gl.deleteFramebuffer(texture._framebuffer);
  16343. texture._framebuffer = null;
  16344. }
  16345. if (texture._depthStencilBuffer) {
  16346. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16347. texture._depthStencilBuffer = null;
  16348. }
  16349. if (texture._MSAAFramebuffer) {
  16350. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16351. texture._MSAAFramebuffer = null;
  16352. }
  16353. if (texture._MSAARenderBuffer) {
  16354. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16355. texture._MSAARenderBuffer = null;
  16356. }
  16357. };
  16358. /** @hidden */
  16359. Engine.prototype._releaseTexture = function (texture) {
  16360. var gl = this._gl;
  16361. this._releaseFramebufferObjects(texture);
  16362. gl.deleteTexture(texture._webGLTexture);
  16363. // Unbind channels
  16364. this.unbindAllTextures();
  16365. var index = this._internalTexturesCache.indexOf(texture);
  16366. if (index !== -1) {
  16367. this._internalTexturesCache.splice(index, 1);
  16368. }
  16369. // Integrated fixed lod samplers.
  16370. if (texture._lodTextureHigh) {
  16371. texture._lodTextureHigh.dispose();
  16372. }
  16373. if (texture._lodTextureMid) {
  16374. texture._lodTextureMid.dispose();
  16375. }
  16376. if (texture._lodTextureLow) {
  16377. texture._lodTextureLow.dispose();
  16378. }
  16379. // Set output texture of post process to null if the texture has been released/disposed
  16380. this.scenes.forEach(function (scene) {
  16381. scene.postProcesses.forEach(function (postProcess) {
  16382. if (postProcess._outputTexture == texture) {
  16383. postProcess._outputTexture = null;
  16384. }
  16385. });
  16386. scene.cameras.forEach(function (camera) {
  16387. camera._postProcesses.forEach(function (postProcess) {
  16388. if (postProcess) {
  16389. if (postProcess._outputTexture == texture) {
  16390. postProcess._outputTexture = null;
  16391. }
  16392. }
  16393. });
  16394. });
  16395. });
  16396. };
  16397. Engine.prototype.setProgram = function (program) {
  16398. if (this._currentProgram !== program) {
  16399. this._gl.useProgram(program);
  16400. this._currentProgram = program;
  16401. }
  16402. };
  16403. /**
  16404. * Binds an effect to the webGL context
  16405. * @param effect defines the effect to bind
  16406. */
  16407. Engine.prototype.bindSamplers = function (effect) {
  16408. this.setProgram(effect.getProgram());
  16409. var samplers = effect.getSamplers();
  16410. for (var index = 0; index < samplers.length; index++) {
  16411. var uniform = effect.getUniform(samplers[index]);
  16412. if (uniform) {
  16413. this._boundUniforms[index] = uniform;
  16414. }
  16415. }
  16416. this._currentEffect = null;
  16417. };
  16418. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16419. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16420. return;
  16421. }
  16422. // Remove
  16423. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16424. // Bind last to it
  16425. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16426. // Bind to dummy
  16427. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16428. };
  16429. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16430. if (!internalTexture) {
  16431. return -1;
  16432. }
  16433. internalTexture._initialSlot = channel;
  16434. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16435. if (channel !== internalTexture._designatedSlot) {
  16436. this._textureCollisions.addCount(1, false);
  16437. }
  16438. }
  16439. else {
  16440. if (channel !== internalTexture._designatedSlot) {
  16441. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16442. return internalTexture._designatedSlot;
  16443. }
  16444. else {
  16445. // No slot for this texture, let's pick a new one (if we find a free slot)
  16446. if (this._nextFreeTextureSlots.length) {
  16447. return this._nextFreeTextureSlots[0];
  16448. }
  16449. // We need to recycle the oldest bound texture, sorry.
  16450. this._textureCollisions.addCount(1, false);
  16451. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16452. }
  16453. }
  16454. }
  16455. return channel;
  16456. };
  16457. Engine.prototype._linkTrackers = function (previous, next) {
  16458. previous.next = next;
  16459. next.previous = previous;
  16460. };
  16461. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16462. var currentSlot = internalTexture._designatedSlot;
  16463. if (currentSlot === -1) {
  16464. return -1;
  16465. }
  16466. internalTexture._designatedSlot = -1;
  16467. if (this.disableTextureBindingOptimization) {
  16468. return -1;
  16469. }
  16470. // Remove from bound list
  16471. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16472. // Free the slot
  16473. this._boundTexturesCache[currentSlot] = null;
  16474. this._nextFreeTextureSlots.push(currentSlot);
  16475. return currentSlot;
  16476. };
  16477. Engine.prototype._activateCurrentTexture = function () {
  16478. if (this._currentTextureChannel !== this._activeChannel) {
  16479. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16480. this._currentTextureChannel = this._activeChannel;
  16481. }
  16482. };
  16483. /** @hidden */
  16484. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16485. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16486. if (force === void 0) { force = false; }
  16487. var wasPreviouslyBound = false;
  16488. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16489. this._activeChannel = texture._designatedSlot;
  16490. }
  16491. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16492. var isTextureForRendering = texture && texture._initialSlot > -1;
  16493. if (currentTextureBound !== texture || force) {
  16494. if (currentTextureBound) {
  16495. this._removeDesignatedSlot(currentTextureBound);
  16496. }
  16497. this._activateCurrentTexture();
  16498. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16499. this._boundTexturesCache[this._activeChannel] = texture;
  16500. if (texture) {
  16501. if (!this.disableTextureBindingOptimization) {
  16502. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16503. if (slotIndex > -1) {
  16504. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16505. }
  16506. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16507. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16508. }
  16509. texture._designatedSlot = this._activeChannel;
  16510. }
  16511. }
  16512. else if (forTextureDataUpdate) {
  16513. wasPreviouslyBound = true;
  16514. this._activateCurrentTexture();
  16515. }
  16516. if (isTextureForRendering && !forTextureDataUpdate) {
  16517. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16518. }
  16519. return wasPreviouslyBound;
  16520. };
  16521. /** @hidden */
  16522. Engine.prototype._bindTexture = function (channel, texture) {
  16523. if (channel < 0) {
  16524. return;
  16525. }
  16526. if (texture) {
  16527. channel = this._getCorrectTextureChannel(channel, texture);
  16528. }
  16529. this._activeChannel = channel;
  16530. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16531. };
  16532. /**
  16533. * Sets a texture to the webGL context from a postprocess
  16534. * @param channel defines the channel to use
  16535. * @param postProcess defines the source postprocess
  16536. */
  16537. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16538. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16539. };
  16540. /**
  16541. * Binds the output of the passed in post process to the texture channel specified
  16542. * @param channel The channel the texture should be bound to
  16543. * @param postProcess The post process which's output should be bound
  16544. */
  16545. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16546. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16547. };
  16548. /**
  16549. * Unbind all textures from the webGL context
  16550. */
  16551. Engine.prototype.unbindAllTextures = function () {
  16552. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16553. this._activeChannel = channel;
  16554. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16555. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16556. if (this.webGLVersion > 1) {
  16557. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16558. }
  16559. }
  16560. };
  16561. /**
  16562. * Sets a texture to the according uniform.
  16563. * @param channel The texture channel
  16564. * @param uniform The uniform to set
  16565. * @param texture The texture to apply
  16566. */
  16567. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16568. if (channel < 0) {
  16569. return;
  16570. }
  16571. if (uniform) {
  16572. this._boundUniforms[channel] = uniform;
  16573. }
  16574. this._setTexture(channel, texture);
  16575. };
  16576. /**
  16577. * Sets a depth stencil texture from a render target to the according uniform.
  16578. * @param channel The texture channel
  16579. * @param uniform The uniform to set
  16580. * @param texture The render target texture containing the depth stencil texture to apply
  16581. */
  16582. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16583. if (channel < 0) {
  16584. return;
  16585. }
  16586. if (uniform) {
  16587. this._boundUniforms[channel] = uniform;
  16588. }
  16589. if (!texture || !texture.depthStencilTexture) {
  16590. this._setTexture(channel, null);
  16591. }
  16592. else {
  16593. this._setTexture(channel, texture, false, true);
  16594. }
  16595. };
  16596. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16597. var uniform = this._boundUniforms[sourceSlot];
  16598. if (uniform._currentState === destination) {
  16599. return;
  16600. }
  16601. this._gl.uniform1i(uniform, destination);
  16602. uniform._currentState = destination;
  16603. };
  16604. Engine.prototype._getTextureWrapMode = function (mode) {
  16605. switch (mode) {
  16606. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16607. return this._gl.REPEAT;
  16608. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16609. return this._gl.CLAMP_TO_EDGE;
  16610. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16611. return this._gl.MIRRORED_REPEAT;
  16612. }
  16613. return this._gl.REPEAT;
  16614. };
  16615. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16616. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16617. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16618. // Not ready?
  16619. if (!texture) {
  16620. if (this._boundTexturesCache[channel] != null) {
  16621. this._activeChannel = channel;
  16622. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16623. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16624. if (this.webGLVersion > 1) {
  16625. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16626. }
  16627. }
  16628. return false;
  16629. }
  16630. // Video
  16631. if (texture.video) {
  16632. this._activeChannel = channel;
  16633. texture.update();
  16634. }
  16635. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16636. texture.delayLoad();
  16637. return false;
  16638. }
  16639. var internalTexture;
  16640. if (depthStencilTexture) {
  16641. internalTexture = texture.depthStencilTexture;
  16642. }
  16643. else if (texture.isReady()) {
  16644. internalTexture = texture.getInternalTexture();
  16645. }
  16646. else if (texture.isCube) {
  16647. internalTexture = this.emptyCubeTexture;
  16648. }
  16649. else if (texture.is3D) {
  16650. internalTexture = this.emptyTexture3D;
  16651. }
  16652. else {
  16653. internalTexture = this.emptyTexture;
  16654. }
  16655. if (!isPartOfTextureArray) {
  16656. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16657. }
  16658. var needToBind = true;
  16659. if (this._boundTexturesCache[channel] === internalTexture) {
  16660. this._moveBoundTextureOnTop(internalTexture);
  16661. if (!isPartOfTextureArray) {
  16662. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16663. }
  16664. needToBind = false;
  16665. }
  16666. this._activeChannel = channel;
  16667. if (internalTexture && internalTexture.is3D) {
  16668. if (needToBind) {
  16669. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16670. }
  16671. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16672. internalTexture._cachedWrapU = texture.wrapU;
  16673. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16674. }
  16675. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16676. internalTexture._cachedWrapV = texture.wrapV;
  16677. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16678. }
  16679. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16680. internalTexture._cachedWrapR = texture.wrapR;
  16681. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16682. }
  16683. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16684. }
  16685. else if (internalTexture && internalTexture.isCube) {
  16686. if (needToBind) {
  16687. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16688. }
  16689. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16690. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16691. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16692. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16693. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16694. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16695. }
  16696. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16697. }
  16698. else {
  16699. if (needToBind) {
  16700. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16701. }
  16702. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16703. internalTexture._cachedWrapU = texture.wrapU;
  16704. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16705. }
  16706. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16707. internalTexture._cachedWrapV = texture.wrapV;
  16708. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16709. }
  16710. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16711. }
  16712. return true;
  16713. };
  16714. /**
  16715. * Sets an array of texture to the webGL context
  16716. * @param channel defines the channel where the texture array must be set
  16717. * @param uniform defines the associated uniform location
  16718. * @param textures defines the array of textures to bind
  16719. */
  16720. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16721. if (channel < 0 || !uniform) {
  16722. return;
  16723. }
  16724. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16725. this._textureUnits = new Int32Array(textures.length);
  16726. }
  16727. for (var i = 0; i < textures.length; i++) {
  16728. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16729. }
  16730. this._gl.uniform1iv(uniform, this._textureUnits);
  16731. for (var index = 0; index < textures.length; index++) {
  16732. this._setTexture(this._textureUnits[index], textures[index], true);
  16733. }
  16734. };
  16735. /** @hidden */
  16736. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16737. var internalTexture = texture.getInternalTexture();
  16738. if (!internalTexture) {
  16739. return;
  16740. }
  16741. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16742. var value = texture.anisotropicFilteringLevel;
  16743. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16744. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16745. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16746. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16747. }
  16748. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16749. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16750. internalTexture._cachedAnisotropicFilteringLevel = value;
  16751. }
  16752. };
  16753. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16754. this._bindTextureDirectly(target, texture, true, true);
  16755. this._gl.texParameterf(target, parameter, value);
  16756. };
  16757. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16758. if (texture) {
  16759. this._bindTextureDirectly(target, texture, true, true);
  16760. }
  16761. this._gl.texParameteri(target, parameter, value);
  16762. };
  16763. /**
  16764. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16765. * @param x defines the x coordinate of the rectangle where pixels must be read
  16766. * @param y defines the y coordinate of the rectangle where pixels must be read
  16767. * @param width defines the width of the rectangle where pixels must be read
  16768. * @param height defines the height of the rectangle where pixels must be read
  16769. * @returns a Uint8Array containing RGBA colors
  16770. */
  16771. Engine.prototype.readPixels = function (x, y, width, height) {
  16772. var data = new Uint8Array(height * width * 4);
  16773. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16774. return data;
  16775. };
  16776. /**
  16777. * Add an externaly attached data from its key.
  16778. * This method call will fail and return false, if such key already exists.
  16779. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16780. * @param key the unique key that identifies the data
  16781. * @param data the data object to associate to the key for this Engine instance
  16782. * @return true if no such key were already present and the data was added successfully, false otherwise
  16783. */
  16784. Engine.prototype.addExternalData = function (key, data) {
  16785. if (!this._externalData) {
  16786. this._externalData = new BABYLON.StringDictionary();
  16787. }
  16788. return this._externalData.add(key, data);
  16789. };
  16790. /**
  16791. * Get an externaly attached data from its key
  16792. * @param key the unique key that identifies the data
  16793. * @return the associated data, if present (can be null), or undefined if not present
  16794. */
  16795. Engine.prototype.getExternalData = function (key) {
  16796. if (!this._externalData) {
  16797. this._externalData = new BABYLON.StringDictionary();
  16798. }
  16799. return this._externalData.get(key);
  16800. };
  16801. /**
  16802. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16803. * @param key the unique key that identifies the data
  16804. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16805. * @return the associated data, can be null if the factory returned null.
  16806. */
  16807. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16808. if (!this._externalData) {
  16809. this._externalData = new BABYLON.StringDictionary();
  16810. }
  16811. return this._externalData.getOrAddWithFactory(key, factory);
  16812. };
  16813. /**
  16814. * Remove an externaly attached data from the Engine instance
  16815. * @param key the unique key that identifies the data
  16816. * @return true if the data was successfully removed, false if it doesn't exist
  16817. */
  16818. Engine.prototype.removeExternalData = function (key) {
  16819. if (!this._externalData) {
  16820. this._externalData = new BABYLON.StringDictionary();
  16821. }
  16822. return this._externalData.remove(key);
  16823. };
  16824. /**
  16825. * Unbind all vertex attributes from the webGL context
  16826. */
  16827. Engine.prototype.unbindAllAttributes = function () {
  16828. if (this._mustWipeVertexAttributes) {
  16829. this._mustWipeVertexAttributes = false;
  16830. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16831. this._gl.disableVertexAttribArray(i);
  16832. this._vertexAttribArraysEnabled[i] = false;
  16833. this._currentBufferPointers[i].active = false;
  16834. }
  16835. return;
  16836. }
  16837. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16838. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16839. continue;
  16840. }
  16841. this._gl.disableVertexAttribArray(i);
  16842. this._vertexAttribArraysEnabled[i] = false;
  16843. this._currentBufferPointers[i].active = false;
  16844. }
  16845. };
  16846. /**
  16847. * 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
  16848. */
  16849. Engine.prototype.releaseEffects = function () {
  16850. for (var name in this._compiledEffects) {
  16851. this._deleteProgram(this._compiledEffects[name]._program);
  16852. }
  16853. this._compiledEffects = {};
  16854. };
  16855. /**
  16856. * Dispose and release all associated resources
  16857. */
  16858. Engine.prototype.dispose = function () {
  16859. this.hideLoadingUI();
  16860. this.stopRenderLoop();
  16861. // Release postProcesses
  16862. while (this.postProcesses.length) {
  16863. this.postProcesses[0].dispose();
  16864. }
  16865. // Empty texture
  16866. if (this._emptyTexture) {
  16867. this._releaseTexture(this._emptyTexture);
  16868. this._emptyTexture = null;
  16869. }
  16870. if (this._emptyCubeTexture) {
  16871. this._releaseTexture(this._emptyCubeTexture);
  16872. this._emptyCubeTexture = null;
  16873. }
  16874. // Rescale PP
  16875. if (this._rescalePostProcess) {
  16876. this._rescalePostProcess.dispose();
  16877. }
  16878. // Release scenes
  16879. while (this.scenes.length) {
  16880. this.scenes[0].dispose();
  16881. }
  16882. // Release audio engine
  16883. if (Engine.audioEngine) {
  16884. Engine.audioEngine.dispose();
  16885. }
  16886. // Release effects
  16887. this.releaseEffects();
  16888. // Unbind
  16889. this.unbindAllAttributes();
  16890. this._boundUniforms = [];
  16891. if (this._dummyFramebuffer) {
  16892. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16893. }
  16894. //WebVR
  16895. this.disableVR();
  16896. // Events
  16897. if (BABYLON.Tools.IsWindowObjectExist()) {
  16898. window.removeEventListener("blur", this._onBlur);
  16899. window.removeEventListener("focus", this._onFocus);
  16900. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16901. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16902. if (this._renderingCanvas) {
  16903. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16904. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16905. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16906. if (!this._doNotHandleContextLost) {
  16907. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16908. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16909. }
  16910. }
  16911. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16912. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16913. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16914. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16915. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16916. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16917. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16918. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16919. if (this._onVrDisplayConnect) {
  16920. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16921. if (this._onVrDisplayDisconnect) {
  16922. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16923. }
  16924. if (this._onVrDisplayPresentChange) {
  16925. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16926. }
  16927. this._onVrDisplayConnect = null;
  16928. this._onVrDisplayDisconnect = null;
  16929. }
  16930. }
  16931. // Remove from Instances
  16932. var index = Engine.Instances.indexOf(this);
  16933. if (index >= 0) {
  16934. Engine.Instances.splice(index, 1);
  16935. }
  16936. this._workingCanvas = null;
  16937. this._workingContext = null;
  16938. this._currentBufferPointers = [];
  16939. this._renderingCanvas = null;
  16940. this._currentProgram = null;
  16941. this._bindedRenderFunction = null;
  16942. this.onResizeObservable.clear();
  16943. this.onCanvasBlurObservable.clear();
  16944. this.onCanvasFocusObservable.clear();
  16945. this.onCanvasPointerOutObservable.clear();
  16946. this.onBeginFrameObservable.clear();
  16947. this.onEndFrameObservable.clear();
  16948. BABYLON.Effect.ResetCache();
  16949. // Abort active requests
  16950. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16951. var request = _a[_i];
  16952. request.abort();
  16953. }
  16954. };
  16955. // Loading screen
  16956. /**
  16957. * Display the loading screen
  16958. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16959. */
  16960. Engine.prototype.displayLoadingUI = function () {
  16961. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16962. return;
  16963. }
  16964. var loadingScreen = this.loadingScreen;
  16965. if (loadingScreen) {
  16966. loadingScreen.displayLoadingUI();
  16967. }
  16968. };
  16969. /**
  16970. * Hide the loading screen
  16971. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16972. */
  16973. Engine.prototype.hideLoadingUI = function () {
  16974. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16975. return;
  16976. }
  16977. var loadingScreen = this.loadingScreen;
  16978. if (loadingScreen) {
  16979. loadingScreen.hideLoadingUI();
  16980. }
  16981. };
  16982. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16983. /**
  16984. * Gets the current loading screen object
  16985. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16986. */
  16987. get: function () {
  16988. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16989. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16990. return this._loadingScreen;
  16991. },
  16992. /**
  16993. * Sets the current loading screen object
  16994. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16995. */
  16996. set: function (loadingScreen) {
  16997. this._loadingScreen = loadingScreen;
  16998. },
  16999. enumerable: true,
  17000. configurable: true
  17001. });
  17002. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17003. /**
  17004. * Sets the current loading screen text
  17005. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17006. */
  17007. set: function (text) {
  17008. this.loadingScreen.loadingUIText = text;
  17009. },
  17010. enumerable: true,
  17011. configurable: true
  17012. });
  17013. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17014. /**
  17015. * Sets the current loading screen background color
  17016. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17017. */
  17018. set: function (color) {
  17019. this.loadingScreen.loadingUIBackgroundColor = color;
  17020. },
  17021. enumerable: true,
  17022. configurable: true
  17023. });
  17024. /**
  17025. * Attach a new callback raised when context lost event is fired
  17026. * @param callback defines the callback to call
  17027. */
  17028. Engine.prototype.attachContextLostEvent = function (callback) {
  17029. if (this._renderingCanvas) {
  17030. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17031. }
  17032. };
  17033. /**
  17034. * Attach a new callback raised when context restored event is fired
  17035. * @param callback defines the callback to call
  17036. */
  17037. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17038. if (this._renderingCanvas) {
  17039. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17040. }
  17041. };
  17042. /**
  17043. * Gets the source code of the vertex shader associated with a specific webGL program
  17044. * @param program defines the program to use
  17045. * @returns a string containing the source code of the vertex shader associated with the program
  17046. */
  17047. Engine.prototype.getVertexShaderSource = function (program) {
  17048. var shaders = this._gl.getAttachedShaders(program);
  17049. if (!shaders) {
  17050. return null;
  17051. }
  17052. return this._gl.getShaderSource(shaders[0]);
  17053. };
  17054. /**
  17055. * Gets the source code of the fragment shader associated with a specific webGL program
  17056. * @param program defines the program to use
  17057. * @returns a string containing the source code of the fragment shader associated with the program
  17058. */
  17059. Engine.prototype.getFragmentShaderSource = function (program) {
  17060. var shaders = this._gl.getAttachedShaders(program);
  17061. if (!shaders) {
  17062. return null;
  17063. }
  17064. return this._gl.getShaderSource(shaders[1]);
  17065. };
  17066. /**
  17067. * Get the current error code of the webGL context
  17068. * @returns the error code
  17069. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17070. */
  17071. Engine.prototype.getError = function () {
  17072. return this._gl.getError();
  17073. };
  17074. // FPS
  17075. /**
  17076. * Gets the current framerate
  17077. * @returns a number representing the framerate
  17078. */
  17079. Engine.prototype.getFps = function () {
  17080. return this._fps;
  17081. };
  17082. /**
  17083. * Gets the time spent between current and previous frame
  17084. * @returns a number representing the delta time in ms
  17085. */
  17086. Engine.prototype.getDeltaTime = function () {
  17087. return this._deltaTime;
  17088. };
  17089. Engine.prototype._measureFps = function () {
  17090. this._performanceMonitor.sampleFrame();
  17091. this._fps = this._performanceMonitor.averageFPS;
  17092. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17093. };
  17094. /** @hidden */
  17095. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17096. if (faceIndex === void 0) { faceIndex = -1; }
  17097. if (level === void 0) { level = 0; }
  17098. var gl = this._gl;
  17099. if (!this._dummyFramebuffer) {
  17100. var dummy = gl.createFramebuffer();
  17101. if (!dummy) {
  17102. throw new Error("Unable to create dummy framebuffer");
  17103. }
  17104. this._dummyFramebuffer = dummy;
  17105. }
  17106. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17107. if (faceIndex > -1) {
  17108. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17109. }
  17110. else {
  17111. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17112. }
  17113. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17114. var buffer;
  17115. switch (readType) {
  17116. case gl.UNSIGNED_BYTE:
  17117. buffer = new Uint8Array(4 * width * height);
  17118. readType = gl.UNSIGNED_BYTE;
  17119. break;
  17120. default:
  17121. buffer = new Float32Array(4 * width * height);
  17122. readType = gl.FLOAT;
  17123. break;
  17124. }
  17125. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17126. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17127. return buffer;
  17128. };
  17129. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17130. if (this._webGLVersion > 1) {
  17131. return this._caps.colorBufferFloat;
  17132. }
  17133. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17134. };
  17135. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17136. if (this._webGLVersion > 1) {
  17137. return this._caps.colorBufferFloat;
  17138. }
  17139. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17140. };
  17141. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17142. Engine.prototype._canRenderToFramebuffer = function (type) {
  17143. var gl = this._gl;
  17144. //clear existing errors
  17145. while (gl.getError() !== gl.NO_ERROR) { }
  17146. var successful = true;
  17147. var texture = gl.createTexture();
  17148. gl.bindTexture(gl.TEXTURE_2D, texture);
  17149. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17152. var fb = gl.createFramebuffer();
  17153. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17154. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17155. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17156. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17157. successful = successful && (gl.getError() === gl.NO_ERROR);
  17158. //try render by clearing frame buffer's color buffer
  17159. if (successful) {
  17160. gl.clear(gl.COLOR_BUFFER_BIT);
  17161. successful = successful && (gl.getError() === gl.NO_ERROR);
  17162. }
  17163. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17164. if (successful) {
  17165. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17166. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17167. var readFormat = gl.RGBA;
  17168. var readType = gl.UNSIGNED_BYTE;
  17169. var buffer = new Uint8Array(4);
  17170. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17171. successful = successful && (gl.getError() === gl.NO_ERROR);
  17172. }
  17173. //clean up
  17174. gl.deleteTexture(texture);
  17175. gl.deleteFramebuffer(fb);
  17176. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17177. //clear accumulated errors
  17178. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17179. return successful;
  17180. };
  17181. /** @hidden */
  17182. Engine.prototype._getWebGLTextureType = function (type) {
  17183. if (type === Engine.TEXTURETYPE_FLOAT) {
  17184. return this._gl.FLOAT;
  17185. }
  17186. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17187. // Add Half Float Constant.
  17188. return this._gl.HALF_FLOAT_OES;
  17189. }
  17190. return this._gl.UNSIGNED_BYTE;
  17191. };
  17192. ;
  17193. Engine.prototype._getInternalFormat = function (format) {
  17194. var internalFormat = this._gl.RGBA;
  17195. switch (format) {
  17196. case Engine.TEXTUREFORMAT_ALPHA:
  17197. internalFormat = this._gl.ALPHA;
  17198. break;
  17199. case Engine.TEXTUREFORMAT_LUMINANCE:
  17200. internalFormat = this._gl.LUMINANCE;
  17201. break;
  17202. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17203. internalFormat = this._gl.LUMINANCE_ALPHA;
  17204. break;
  17205. case Engine.TEXTUREFORMAT_RGB:
  17206. internalFormat = this._gl.RGB;
  17207. break;
  17208. case Engine.TEXTUREFORMAT_RGBA:
  17209. internalFormat = this._gl.RGBA;
  17210. break;
  17211. case Engine.TEXTUREFORMAT_R:
  17212. internalFormat = this._gl.RED;
  17213. break;
  17214. case Engine.TEXTUREFORMAT_RG:
  17215. internalFormat = this._gl.RG;
  17216. break;
  17217. }
  17218. return internalFormat;
  17219. };
  17220. /** @hidden */
  17221. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17222. if (this._webGLVersion === 1) {
  17223. if (format !== undefined) {
  17224. switch (format) {
  17225. case Engine.TEXTUREFORMAT_LUMINANCE:
  17226. return this._gl.LUMINANCE;
  17227. case Engine.TEXTUREFORMAT_ALPHA:
  17228. return this._gl.ALPHA;
  17229. }
  17230. }
  17231. return this._gl.RGBA;
  17232. }
  17233. if (type === Engine.TEXTURETYPE_FLOAT) {
  17234. if (format !== undefined) {
  17235. switch (format) {
  17236. case Engine.TEXTUREFORMAT_R:
  17237. return this._gl.R32F;
  17238. case Engine.TEXTUREFORMAT_RG:
  17239. return this._gl.RG32F;
  17240. case Engine.TEXTUREFORMAT_RGB:
  17241. return this._gl.RGB32F;
  17242. }
  17243. }
  17244. return this._gl.RGBA32F;
  17245. }
  17246. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17247. if (format) {
  17248. switch (format) {
  17249. case Engine.TEXTUREFORMAT_R:
  17250. return this._gl.R16F;
  17251. case Engine.TEXTUREFORMAT_RG:
  17252. return this._gl.RG16F;
  17253. case Engine.TEXTUREFORMAT_RGB:
  17254. return this._gl.RGB16F;
  17255. }
  17256. }
  17257. return this._gl.RGBA16F;
  17258. }
  17259. if (format !== undefined) {
  17260. switch (format) {
  17261. case Engine.TEXTUREFORMAT_LUMINANCE:
  17262. return this._gl.LUMINANCE;
  17263. case Engine.TEXTUREFORMAT_RGB:
  17264. return this._gl.RGB;
  17265. case Engine.TEXTUREFORMAT_R:
  17266. return this._gl.R8;
  17267. case Engine.TEXTUREFORMAT_RG:
  17268. return this._gl.RG8;
  17269. case Engine.TEXTUREFORMAT_ALPHA:
  17270. return this._gl.ALPHA;
  17271. }
  17272. }
  17273. return this._gl.RGBA;
  17274. };
  17275. ;
  17276. /** @hidden */
  17277. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17278. if (type === Engine.TEXTURETYPE_FLOAT) {
  17279. return this._gl.RGBA32F;
  17280. }
  17281. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17282. return this._gl.RGBA16F;
  17283. }
  17284. return this._gl.RGBA8;
  17285. };
  17286. ;
  17287. /**
  17288. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17289. * @return the new query
  17290. */
  17291. Engine.prototype.createQuery = function () {
  17292. return this._gl.createQuery();
  17293. };
  17294. /**
  17295. * Delete and release a webGL query
  17296. * @param query defines the query to delete
  17297. * @return the current engine
  17298. */
  17299. Engine.prototype.deleteQuery = function (query) {
  17300. this._gl.deleteQuery(query);
  17301. return this;
  17302. };
  17303. /**
  17304. * Check if a given query has resolved and got its value
  17305. * @param query defines the query to check
  17306. * @returns true if the query got its value
  17307. */
  17308. Engine.prototype.isQueryResultAvailable = function (query) {
  17309. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17310. };
  17311. /**
  17312. * Gets the value of a given query
  17313. * @param query defines the query to check
  17314. * @returns the value of the query
  17315. */
  17316. Engine.prototype.getQueryResult = function (query) {
  17317. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17318. };
  17319. /**
  17320. * Initiates an occlusion query
  17321. * @param algorithmType defines the algorithm to use
  17322. * @param query defines the query to use
  17323. * @returns the current engine
  17324. * @see http://doc.babylonjs.com/features/occlusionquery
  17325. */
  17326. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17327. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17328. this._gl.beginQuery(glAlgorithm, query);
  17329. return this;
  17330. };
  17331. /**
  17332. * Ends an occlusion query
  17333. * @see http://doc.babylonjs.com/features/occlusionquery
  17334. * @param algorithmType defines the algorithm to use
  17335. * @returns the current engine
  17336. */
  17337. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17338. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17339. this._gl.endQuery(glAlgorithm);
  17340. return this;
  17341. };
  17342. /* Time queries */
  17343. Engine.prototype._createTimeQuery = function () {
  17344. var timerQuery = this._caps.timerQuery;
  17345. if (timerQuery.createQueryEXT) {
  17346. return timerQuery.createQueryEXT();
  17347. }
  17348. return this.createQuery();
  17349. };
  17350. Engine.prototype._deleteTimeQuery = function (query) {
  17351. var timerQuery = this._caps.timerQuery;
  17352. if (timerQuery.deleteQueryEXT) {
  17353. timerQuery.deleteQueryEXT(query);
  17354. return;
  17355. }
  17356. this.deleteQuery(query);
  17357. };
  17358. Engine.prototype._getTimeQueryResult = function (query) {
  17359. var timerQuery = this._caps.timerQuery;
  17360. if (timerQuery.getQueryObjectEXT) {
  17361. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17362. }
  17363. return this.getQueryResult(query);
  17364. };
  17365. Engine.prototype._getTimeQueryAvailability = function (query) {
  17366. var timerQuery = this._caps.timerQuery;
  17367. if (timerQuery.getQueryObjectEXT) {
  17368. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17369. }
  17370. return this.isQueryResultAvailable(query);
  17371. };
  17372. /**
  17373. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17374. * Please note that only one query can be issued at a time
  17375. * @returns a time token used to track the time span
  17376. */
  17377. Engine.prototype.startTimeQuery = function () {
  17378. var timerQuery = this._caps.timerQuery;
  17379. if (!timerQuery) {
  17380. return null;
  17381. }
  17382. var token = new BABYLON._TimeToken();
  17383. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17384. if (this._caps.canUseTimestampForTimerQuery) {
  17385. token._startTimeQuery = this._createTimeQuery();
  17386. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17387. }
  17388. else {
  17389. if (this._currentNonTimestampToken) {
  17390. return this._currentNonTimestampToken;
  17391. }
  17392. token._timeElapsedQuery = this._createTimeQuery();
  17393. if (timerQuery.beginQueryEXT) {
  17394. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17395. }
  17396. else {
  17397. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17398. }
  17399. this._currentNonTimestampToken = token;
  17400. }
  17401. return token;
  17402. };
  17403. /**
  17404. * Ends a time query
  17405. * @param token defines the token used to measure the time span
  17406. * @returns the time spent (in ns)
  17407. */
  17408. Engine.prototype.endTimeQuery = function (token) {
  17409. var timerQuery = this._caps.timerQuery;
  17410. if (!timerQuery || !token) {
  17411. return -1;
  17412. }
  17413. if (this._caps.canUseTimestampForTimerQuery) {
  17414. if (!token._startTimeQuery) {
  17415. return -1;
  17416. }
  17417. if (!token._endTimeQuery) {
  17418. token._endTimeQuery = this._createTimeQuery();
  17419. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17420. }
  17421. }
  17422. else if (!token._timeElapsedQueryEnded) {
  17423. if (!token._timeElapsedQuery) {
  17424. return -1;
  17425. }
  17426. if (timerQuery.endQueryEXT) {
  17427. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17428. }
  17429. else {
  17430. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17431. }
  17432. token._timeElapsedQueryEnded = true;
  17433. }
  17434. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17435. var available = false;
  17436. if (token._endTimeQuery) {
  17437. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17438. }
  17439. else if (token._timeElapsedQuery) {
  17440. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17441. }
  17442. if (available && !disjoint) {
  17443. var result = 0;
  17444. if (this._caps.canUseTimestampForTimerQuery) {
  17445. if (!token._startTimeQuery || !token._endTimeQuery) {
  17446. return -1;
  17447. }
  17448. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17449. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17450. result = timeEnd - timeStart;
  17451. this._deleteTimeQuery(token._startTimeQuery);
  17452. this._deleteTimeQuery(token._endTimeQuery);
  17453. token._startTimeQuery = null;
  17454. token._endTimeQuery = null;
  17455. }
  17456. else {
  17457. if (!token._timeElapsedQuery) {
  17458. return -1;
  17459. }
  17460. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17461. this._deleteTimeQuery(token._timeElapsedQuery);
  17462. token._timeElapsedQuery = null;
  17463. token._timeElapsedQueryEnded = false;
  17464. this._currentNonTimestampToken = null;
  17465. }
  17466. return result;
  17467. }
  17468. return -1;
  17469. };
  17470. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17471. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17472. };
  17473. // Transform feedback
  17474. /**
  17475. * Creates a webGL transform feedback object
  17476. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17477. * @returns the webGL transform feedback object
  17478. */
  17479. Engine.prototype.createTransformFeedback = function () {
  17480. return this._gl.createTransformFeedback();
  17481. };
  17482. /**
  17483. * Delete a webGL transform feedback object
  17484. * @param value defines the webGL transform feedback object to delete
  17485. */
  17486. Engine.prototype.deleteTransformFeedback = function (value) {
  17487. this._gl.deleteTransformFeedback(value);
  17488. };
  17489. /**
  17490. * Bind a webGL transform feedback object to the webgl context
  17491. * @param value defines the webGL transform feedback object to bind
  17492. */
  17493. Engine.prototype.bindTransformFeedback = function (value) {
  17494. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17495. };
  17496. /**
  17497. * Begins a transform feedback operation
  17498. * @param usePoints defines if points or triangles must be used
  17499. */
  17500. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17501. if (usePoints === void 0) { usePoints = true; }
  17502. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17503. };
  17504. /**
  17505. * Ends a transform feedback operation
  17506. */
  17507. Engine.prototype.endTransformFeedback = function () {
  17508. this._gl.endTransformFeedback();
  17509. };
  17510. /**
  17511. * Specify the varyings to use with transform feedback
  17512. * @param program defines the associated webGL program
  17513. * @param value defines the list of strings representing the varying names
  17514. */
  17515. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17516. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17517. };
  17518. /**
  17519. * Bind a webGL buffer for a transform feedback operation
  17520. * @param value defines the webGL buffer to bind
  17521. */
  17522. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17523. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17524. };
  17525. /** @hidden */
  17526. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17527. var _this = this;
  17528. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17529. this._activeRequests.push(request);
  17530. request.onCompleteObservable.add(function (request) {
  17531. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17532. });
  17533. return request;
  17534. };
  17535. /** @hidden */
  17536. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17537. var _this = this;
  17538. return new Promise(function (resolve, reject) {
  17539. _this._loadFile(url, function (data) {
  17540. resolve(data);
  17541. }, undefined, database, useArrayBuffer, function (request, exception) {
  17542. reject(exception);
  17543. });
  17544. });
  17545. };
  17546. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17547. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17548. var onload = function (data) {
  17549. loadedFiles[index] = data;
  17550. loadedFiles._internalCount++;
  17551. if (loadedFiles._internalCount === 6) {
  17552. onfinish(loadedFiles);
  17553. }
  17554. };
  17555. var onerror = function (request, exception) {
  17556. if (onErrorCallBack && request) {
  17557. onErrorCallBack(request.status + " " + request.statusText, exception);
  17558. }
  17559. };
  17560. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17561. };
  17562. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17563. if (onError === void 0) { onError = null; }
  17564. var loadedFiles = [];
  17565. loadedFiles._internalCount = 0;
  17566. for (var index = 0; index < 6; index++) {
  17567. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17568. }
  17569. };
  17570. // Statics
  17571. /**
  17572. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17573. * @returns true if the engine can be created
  17574. * @ignorenaming
  17575. */
  17576. Engine.isSupported = function () {
  17577. try {
  17578. var tempcanvas = document.createElement("canvas");
  17579. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17580. return gl != null && !!window.WebGLRenderingContext;
  17581. }
  17582. catch (e) {
  17583. return false;
  17584. }
  17585. };
  17586. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17587. Engine.ExceptionList = [
  17588. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17589. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17590. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17591. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17592. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17593. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17594. ];
  17595. /** Gets the list of created engines */
  17596. Engine.Instances = new Array();
  17597. // Const statics
  17598. Engine._ALPHA_DISABLE = 0;
  17599. Engine._ALPHA_ADD = 1;
  17600. Engine._ALPHA_COMBINE = 2;
  17601. Engine._ALPHA_SUBTRACT = 3;
  17602. Engine._ALPHA_MULTIPLY = 4;
  17603. Engine._ALPHA_MAXIMIZED = 5;
  17604. Engine._ALPHA_ONEONE = 6;
  17605. Engine._ALPHA_PREMULTIPLIED = 7;
  17606. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17607. Engine._ALPHA_INTERPOLATE = 9;
  17608. Engine._ALPHA_SCREENMODE = 10;
  17609. Engine._DELAYLOADSTATE_NONE = 0;
  17610. Engine._DELAYLOADSTATE_LOADED = 1;
  17611. Engine._DELAYLOADSTATE_LOADING = 2;
  17612. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17613. Engine._TEXTUREFORMAT_ALPHA = 0;
  17614. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17615. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17616. Engine._TEXTUREFORMAT_RGB = 4;
  17617. Engine._TEXTUREFORMAT_RGBA = 5;
  17618. Engine._TEXTUREFORMAT_R = 6;
  17619. Engine._TEXTUREFORMAT_RG = 7;
  17620. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17621. Engine._TEXTURETYPE_FLOAT = 1;
  17622. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17623. // Depht or Stencil test Constants.
  17624. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17625. 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.
  17626. 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.
  17627. 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.
  17628. 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.
  17629. 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.
  17630. 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.
  17631. 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.
  17632. // Stencil Actions Constants.
  17633. Engine._KEEP = 0x1E00;
  17634. Engine._REPLACE = 0x1E01;
  17635. Engine._INCR = 0x1E02;
  17636. Engine._DECR = 0x1E03;
  17637. Engine._INVERT = 0x150A;
  17638. Engine._INCR_WRAP = 0x8507;
  17639. Engine._DECR_WRAP = 0x8508;
  17640. // Texture rescaling mode
  17641. Engine._SCALEMODE_FLOOR = 1;
  17642. Engine._SCALEMODE_NEAREST = 2;
  17643. Engine._SCALEMODE_CEILING = 3;
  17644. // Updatable statics so stick with vars here
  17645. /**
  17646. * Gets or sets the epsilon value used by collision engine
  17647. */
  17648. Engine.CollisionsEpsilon = 0.001;
  17649. /**
  17650. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17651. */
  17652. Engine.CodeRepository = "src/";
  17653. /**
  17654. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17655. */
  17656. Engine.ShadersRepository = "src/Shaders/";
  17657. return Engine;
  17658. }());
  17659. BABYLON.Engine = Engine;
  17660. })(BABYLON || (BABYLON = {}));
  17661. //# sourceMappingURL=babylon.engine.js.map
  17662. var BABYLON;
  17663. (function (BABYLON) {
  17664. /**
  17665. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17666. */
  17667. var Node = /** @class */ (function () {
  17668. /**
  17669. * Creates a new Node
  17670. * @param {string} name - the name and id to be given to this node
  17671. * @param {BABYLON.Scene} the scene this node will be added to
  17672. */
  17673. function Node(name, scene) {
  17674. if (scene === void 0) { scene = null; }
  17675. /**
  17676. * Gets or sets a string used to store user defined state for the node
  17677. */
  17678. this.state = "";
  17679. /**
  17680. * Gets or sets an object used to store user defined information for the node
  17681. */
  17682. this.metadata = null;
  17683. /**
  17684. * Gets or sets a boolean used to define if the node must be serialized
  17685. */
  17686. this.doNotSerialize = false;
  17687. /** @hidden */
  17688. this._isDisposed = false;
  17689. /**
  17690. * Gets a list of Animations associated with the node
  17691. */
  17692. this.animations = new Array();
  17693. this._ranges = {};
  17694. this._isEnabled = true;
  17695. this._isReady = true;
  17696. /** @hidden */
  17697. this._currentRenderId = -1;
  17698. this._parentRenderId = -1;
  17699. this._childRenderId = -1;
  17700. this._animationPropertiesOverride = null;
  17701. /**
  17702. * An event triggered when the mesh is disposed
  17703. */
  17704. this.onDisposeObservable = new BABYLON.Observable();
  17705. // Behaviors
  17706. this._behaviors = new Array();
  17707. this.name = name;
  17708. this.id = name;
  17709. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17710. this.uniqueId = this._scene.getUniqueId();
  17711. this._initCache();
  17712. }
  17713. /**
  17714. * Gets a boolean indicating if the node has been disposed
  17715. * @returns true if the node was disposed
  17716. */
  17717. Node.prototype.isDisposed = function () {
  17718. return this._isDisposed;
  17719. };
  17720. Object.defineProperty(Node.prototype, "parent", {
  17721. get: function () {
  17722. return this._parentNode;
  17723. },
  17724. /**
  17725. * Gets or sets the parent of the node
  17726. */
  17727. set: function (parent) {
  17728. if (this._parentNode === parent) {
  17729. return;
  17730. }
  17731. // Remove self from list of children of parent
  17732. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17733. var index = this._parentNode._children.indexOf(this);
  17734. if (index !== -1) {
  17735. this._parentNode._children.splice(index, 1);
  17736. }
  17737. }
  17738. // Store new parent
  17739. this._parentNode = parent;
  17740. // Add as child to new parent
  17741. if (this._parentNode) {
  17742. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17743. this._parentNode._children = new Array();
  17744. }
  17745. this._parentNode._children.push(this);
  17746. }
  17747. },
  17748. enumerable: true,
  17749. configurable: true
  17750. });
  17751. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17752. /**
  17753. * Gets or sets the animation properties override
  17754. */
  17755. get: function () {
  17756. if (!this._animationPropertiesOverride) {
  17757. return this._scene.animationPropertiesOverride;
  17758. }
  17759. return this._animationPropertiesOverride;
  17760. },
  17761. set: function (value) {
  17762. this._animationPropertiesOverride = value;
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. /**
  17768. * Gets a string idenfifying the name of the class
  17769. * @returns "Node" string
  17770. */
  17771. Node.prototype.getClassName = function () {
  17772. return "Node";
  17773. };
  17774. Object.defineProperty(Node.prototype, "onDispose", {
  17775. /**
  17776. * Sets a callback that will be raised when the node will be disposed
  17777. */
  17778. set: function (callback) {
  17779. if (this._onDisposeObserver) {
  17780. this.onDisposeObservable.remove(this._onDisposeObserver);
  17781. }
  17782. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. /**
  17788. * Gets the scene of the node
  17789. * @returns a {BABYLON.Scene}
  17790. */
  17791. Node.prototype.getScene = function () {
  17792. return this._scene;
  17793. };
  17794. /**
  17795. * Gets the engine of the node
  17796. * @returns a {BABYLON.Engine}
  17797. */
  17798. Node.prototype.getEngine = function () {
  17799. return this._scene.getEngine();
  17800. };
  17801. /**
  17802. * Attach a behavior to the node
  17803. * @see http://doc.babylonjs.com/features/behaviour
  17804. * @param behavior defines the behavior to attach
  17805. * @returns the current Node
  17806. */
  17807. Node.prototype.addBehavior = function (behavior) {
  17808. var _this = this;
  17809. var index = this._behaviors.indexOf(behavior);
  17810. if (index !== -1) {
  17811. return this;
  17812. }
  17813. behavior.init();
  17814. if (this._scene.isLoading) {
  17815. // We defer the attach when the scene will be loaded
  17816. this._scene.onDataLoadedObservable.addOnce(function () {
  17817. behavior.attach(_this);
  17818. });
  17819. }
  17820. else {
  17821. behavior.attach(this);
  17822. }
  17823. this._behaviors.push(behavior);
  17824. return this;
  17825. };
  17826. /**
  17827. * Remove an attached behavior
  17828. * @see http://doc.babylonjs.com/features/behaviour
  17829. * @param behavior defines the behavior to attach
  17830. * @returns the current Node
  17831. */
  17832. Node.prototype.removeBehavior = function (behavior) {
  17833. var index = this._behaviors.indexOf(behavior);
  17834. if (index === -1) {
  17835. return this;
  17836. }
  17837. this._behaviors[index].detach();
  17838. this._behaviors.splice(index, 1);
  17839. return this;
  17840. };
  17841. Object.defineProperty(Node.prototype, "behaviors", {
  17842. /**
  17843. * Gets the list of attached behaviors
  17844. * @see http://doc.babylonjs.com/features/behaviour
  17845. */
  17846. get: function () {
  17847. return this._behaviors;
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. /**
  17853. * Gets an attached behavior by name
  17854. * @param name defines the name of the behavior to look for
  17855. * @see http://doc.babylonjs.com/features/behaviour
  17856. * @returns null if behavior was not found else the requested behavior
  17857. */
  17858. Node.prototype.getBehaviorByName = function (name) {
  17859. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17860. var behavior = _a[_i];
  17861. if (behavior.name === name) {
  17862. return behavior;
  17863. }
  17864. }
  17865. return null;
  17866. };
  17867. /**
  17868. * Returns the world matrix of the node
  17869. * @returns a matrix containing the node's world matrix
  17870. */
  17871. Node.prototype.getWorldMatrix = function () {
  17872. return BABYLON.Matrix.Identity();
  17873. };
  17874. /** @hidden */
  17875. Node.prototype._getWorldMatrixDeterminant = function () {
  17876. return 1;
  17877. };
  17878. // override it in derived class if you add new variables to the cache
  17879. // and call the parent class method
  17880. /** @hidden */
  17881. Node.prototype._initCache = function () {
  17882. this._cache = {};
  17883. this._cache.parent = undefined;
  17884. };
  17885. /** @hidden */
  17886. Node.prototype.updateCache = function (force) {
  17887. if (!force && this.isSynchronized())
  17888. return;
  17889. this._cache.parent = this.parent;
  17890. this._updateCache();
  17891. };
  17892. // override it in derived class if you add new variables to the cache
  17893. // and call the parent class method if !ignoreParentClass
  17894. /** @hidden */
  17895. Node.prototype._updateCache = function (ignoreParentClass) {
  17896. };
  17897. // override it in derived class if you add new variables to the cache
  17898. /** @hidden */
  17899. Node.prototype._isSynchronized = function () {
  17900. return true;
  17901. };
  17902. /** @hidden */
  17903. Node.prototype._markSyncedWithParent = function () {
  17904. if (this.parent) {
  17905. this._parentRenderId = this.parent._childRenderId;
  17906. }
  17907. };
  17908. /** @hidden */
  17909. Node.prototype.isSynchronizedWithParent = function () {
  17910. if (!this.parent) {
  17911. return true;
  17912. }
  17913. if (this._parentRenderId !== this.parent._childRenderId) {
  17914. return false;
  17915. }
  17916. return this.parent.isSynchronized();
  17917. };
  17918. /** @hidden */
  17919. Node.prototype.isSynchronized = function (updateCache) {
  17920. var check = this.hasNewParent();
  17921. check = check || !this.isSynchronizedWithParent();
  17922. check = check || !this._isSynchronized();
  17923. if (updateCache)
  17924. this.updateCache(true);
  17925. return !check;
  17926. };
  17927. /** @hidden */
  17928. Node.prototype.hasNewParent = function (update) {
  17929. if (this._cache.parent === this.parent)
  17930. return false;
  17931. if (update)
  17932. this._cache.parent = this.parent;
  17933. return true;
  17934. };
  17935. /**
  17936. * Is this node ready to be used/rendered
  17937. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17938. * @return true if the node is ready
  17939. */
  17940. Node.prototype.isReady = function (completeCheck) {
  17941. if (completeCheck === void 0) { completeCheck = false; }
  17942. return this._isReady;
  17943. };
  17944. /**
  17945. * Is this node enabled?
  17946. * 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
  17947. * @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
  17948. * @return whether this node (and its parent) is enabled
  17949. */
  17950. Node.prototype.isEnabled = function (checkAncestors) {
  17951. if (checkAncestors === void 0) { checkAncestors = true; }
  17952. if (checkAncestors === false) {
  17953. return this._isEnabled;
  17954. }
  17955. if (this._isEnabled === false) {
  17956. return false;
  17957. }
  17958. if (this.parent !== undefined && this.parent !== null) {
  17959. return this.parent.isEnabled(checkAncestors);
  17960. }
  17961. return true;
  17962. };
  17963. /**
  17964. * Set the enabled state of this node
  17965. * @param value defines the new enabled state
  17966. */
  17967. Node.prototype.setEnabled = function (value) {
  17968. this._isEnabled = value;
  17969. };
  17970. /**
  17971. * Is this node a descendant of the given node?
  17972. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17973. * @param ancestor defines the parent node to inspect
  17974. * @returns a boolean indicating if this node is a descendant of the given node
  17975. */
  17976. Node.prototype.isDescendantOf = function (ancestor) {
  17977. if (this.parent) {
  17978. if (this.parent === ancestor) {
  17979. return true;
  17980. }
  17981. return this.parent.isDescendantOf(ancestor);
  17982. }
  17983. return false;
  17984. };
  17985. /** @hidden */
  17986. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17987. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17988. if (!this._children) {
  17989. return;
  17990. }
  17991. for (var index = 0; index < this._children.length; index++) {
  17992. var item = this._children[index];
  17993. if (!predicate || predicate(item)) {
  17994. results.push(item);
  17995. }
  17996. if (!directDescendantsOnly) {
  17997. item._getDescendants(results, false, predicate);
  17998. }
  17999. }
  18000. };
  18001. /**
  18002. * Will return all nodes that have this node as ascendant
  18003. * @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
  18004. * @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
  18005. * @return all children nodes of all types
  18006. */
  18007. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18008. var results = new Array();
  18009. this._getDescendants(results, directDescendantsOnly, predicate);
  18010. return results;
  18011. };
  18012. /**
  18013. * Get all child-meshes of this node
  18014. * @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
  18015. * @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
  18016. * @returns an array of {BABYLON.AbstractMesh}
  18017. */
  18018. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18019. var results = [];
  18020. this._getDescendants(results, directDescendantsOnly, function (node) {
  18021. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18022. });
  18023. return results;
  18024. };
  18025. /**
  18026. * Get all child-transformNodes of this node
  18027. * @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
  18028. * @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
  18029. * @returns an array of {BABYLON.TransformNode}
  18030. */
  18031. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18032. var results = [];
  18033. this._getDescendants(results, directDescendantsOnly, function (node) {
  18034. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18035. });
  18036. return results;
  18037. };
  18038. /**
  18039. * Get all direct children of this node
  18040. * @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
  18041. * @returns an array of {BABYLON.Node}
  18042. */
  18043. Node.prototype.getChildren = function (predicate) {
  18044. return this.getDescendants(true, predicate);
  18045. };
  18046. /** @hidden */
  18047. Node.prototype._setReady = function (state) {
  18048. if (state === this._isReady) {
  18049. return;
  18050. }
  18051. if (!state) {
  18052. this._isReady = false;
  18053. return;
  18054. }
  18055. if (this.onReady) {
  18056. this.onReady(this);
  18057. }
  18058. this._isReady = true;
  18059. };
  18060. /**
  18061. * Get an animation by name
  18062. * @param name defines the name of the animation to look for
  18063. * @returns null if not found else the requested animation
  18064. */
  18065. Node.prototype.getAnimationByName = function (name) {
  18066. for (var i = 0; i < this.animations.length; i++) {
  18067. var animation = this.animations[i];
  18068. if (animation.name === name) {
  18069. return animation;
  18070. }
  18071. }
  18072. return null;
  18073. };
  18074. /**
  18075. * Creates an animation range for this node
  18076. * @param name defines the name of the range
  18077. * @param from defines the starting key
  18078. * @param to defines the end key
  18079. */
  18080. Node.prototype.createAnimationRange = function (name, from, to) {
  18081. // check name not already in use
  18082. if (!this._ranges[name]) {
  18083. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18084. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18085. if (this.animations[i]) {
  18086. this.animations[i].createRange(name, from, to);
  18087. }
  18088. }
  18089. }
  18090. };
  18091. /**
  18092. * Delete a specific animation range
  18093. * @param name defines the name of the range to delete
  18094. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18095. */
  18096. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18097. if (deleteFrames === void 0) { deleteFrames = true; }
  18098. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18099. if (this.animations[i]) {
  18100. this.animations[i].deleteRange(name, deleteFrames);
  18101. }
  18102. }
  18103. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18104. };
  18105. /**
  18106. * Get an animation range by name
  18107. * @param name defines the name of the animation range to look for
  18108. * @returns null if not found else the requested animation range
  18109. */
  18110. Node.prototype.getAnimationRange = function (name) {
  18111. return this._ranges[name];
  18112. };
  18113. /**
  18114. * Will start the animation sequence
  18115. * @param name defines the range frames for animation sequence
  18116. * @param loop defines if the animation should loop (false by default)
  18117. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18118. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18119. * @returns the object created for this animation. If range does not exist, it will return null
  18120. */
  18121. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18122. var range = this.getAnimationRange(name);
  18123. if (!range) {
  18124. return null;
  18125. }
  18126. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18127. };
  18128. /**
  18129. * Serialize animation ranges into a JSON compatible object
  18130. * @returns serialization object
  18131. */
  18132. Node.prototype.serializeAnimationRanges = function () {
  18133. var serializationRanges = [];
  18134. for (var name in this._ranges) {
  18135. var localRange = this._ranges[name];
  18136. if (!localRange) {
  18137. continue;
  18138. }
  18139. var range = {};
  18140. range.name = name;
  18141. range.from = localRange.from;
  18142. range.to = localRange.to;
  18143. serializationRanges.push(range);
  18144. }
  18145. return serializationRanges;
  18146. };
  18147. /**
  18148. * Computes the world matrix of the node
  18149. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18150. * @returns the world matrix
  18151. */
  18152. Node.prototype.computeWorldMatrix = function (force) {
  18153. return BABYLON.Matrix.Identity();
  18154. };
  18155. /**
  18156. * Releases resources associated with this node.
  18157. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18158. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18159. */
  18160. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18161. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18162. if (!doNotRecurse) {
  18163. var nodes = this.getDescendants(true);
  18164. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18165. var node = nodes_1[_i];
  18166. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18167. }
  18168. }
  18169. else {
  18170. var transformNodes = this.getChildTransformNodes(true);
  18171. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18172. var transformNode = transformNodes_1[_a];
  18173. transformNode.parent = null;
  18174. transformNode.computeWorldMatrix(true);
  18175. }
  18176. }
  18177. this.parent = null;
  18178. // Callback
  18179. this.onDisposeObservable.notifyObservers(this);
  18180. this.onDisposeObservable.clear();
  18181. // Behaviors
  18182. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18183. var behavior = _c[_b];
  18184. behavior.detach();
  18185. }
  18186. this._behaviors = [];
  18187. this._isDisposed = true;
  18188. };
  18189. /**
  18190. * Parse animation range data from a serialization object and store them into a given node
  18191. * @param node defines where to store the animation ranges
  18192. * @param parsedNode defines the serialization object to read data from
  18193. * @param scene defines the hosting scene
  18194. */
  18195. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18196. if (parsedNode.ranges) {
  18197. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18198. var data = parsedNode.ranges[index];
  18199. node.createAnimationRange(data.name, data.from, data.to);
  18200. }
  18201. }
  18202. };
  18203. __decorate([
  18204. BABYLON.serialize()
  18205. ], Node.prototype, "name", void 0);
  18206. __decorate([
  18207. BABYLON.serialize()
  18208. ], Node.prototype, "id", void 0);
  18209. __decorate([
  18210. BABYLON.serialize()
  18211. ], Node.prototype, "uniqueId", void 0);
  18212. __decorate([
  18213. BABYLON.serialize()
  18214. ], Node.prototype, "state", void 0);
  18215. __decorate([
  18216. BABYLON.serialize()
  18217. ], Node.prototype, "metadata", void 0);
  18218. return Node;
  18219. }());
  18220. BABYLON.Node = Node;
  18221. })(BABYLON || (BABYLON = {}));
  18222. //# sourceMappingURL=babylon.node.js.map
  18223. var BABYLON;
  18224. (function (BABYLON) {
  18225. var BoundingSphere = /** @class */ (function () {
  18226. /**
  18227. * Creates a new bounding sphere
  18228. * @param min defines the minimum vector (in local space)
  18229. * @param max defines the maximum vector (in local space)
  18230. */
  18231. function BoundingSphere(min, max) {
  18232. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18233. this.reConstruct(min, max);
  18234. }
  18235. /**
  18236. * Recreates the entire bounding sphere from scratch
  18237. * @param min defines the new minimum vector (in local space)
  18238. * @param max defines the new maximum vector (in local space)
  18239. */
  18240. BoundingSphere.prototype.reConstruct = function (min, max) {
  18241. this.minimum = min.clone();
  18242. this.maximum = max.clone();
  18243. var distance = BABYLON.Vector3.Distance(min, max);
  18244. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18245. this.radius = distance * 0.5;
  18246. this.centerWorld = BABYLON.Vector3.Zero();
  18247. this._update(BABYLON.Matrix.Identity());
  18248. };
  18249. // Methods
  18250. BoundingSphere.prototype._update = function (world) {
  18251. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18252. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18253. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18254. };
  18255. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18256. for (var i = 0; i < 6; i++) {
  18257. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18258. return false;
  18259. }
  18260. return true;
  18261. };
  18262. BoundingSphere.prototype.intersectsPoint = function (point) {
  18263. var x = this.centerWorld.x - point.x;
  18264. var y = this.centerWorld.y - point.y;
  18265. var z = this.centerWorld.z - point.z;
  18266. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18267. if (this.radiusWorld < distance)
  18268. return false;
  18269. return true;
  18270. };
  18271. // Statics
  18272. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18273. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18274. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18275. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18276. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18277. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18278. return false;
  18279. return true;
  18280. };
  18281. return BoundingSphere;
  18282. }());
  18283. BABYLON.BoundingSphere = BoundingSphere;
  18284. })(BABYLON || (BABYLON = {}));
  18285. //# sourceMappingURL=babylon.boundingSphere.js.map
  18286. var BABYLON;
  18287. (function (BABYLON) {
  18288. var BoundingBox = /** @class */ (function () {
  18289. /**
  18290. * Creates a new bounding box
  18291. * @param min defines the minimum vector (in local space)
  18292. * @param max defines the maximum vector (in local space)
  18293. */
  18294. function BoundingBox(min, max) {
  18295. this.vectorsWorld = new Array();
  18296. this.reConstruct(min, max);
  18297. }
  18298. // Methods
  18299. /**
  18300. * Recreates the entire bounding box from scratch
  18301. * @param min defines the new minimum vector (in local space)
  18302. * @param max defines the new maximum vector (in local space)
  18303. */
  18304. BoundingBox.prototype.reConstruct = function (min, max) {
  18305. this.minimum = min.clone();
  18306. this.maximum = max.clone();
  18307. // Bounding vectors
  18308. this.vectors = new Array();
  18309. this.vectors.push(this.minimum.clone());
  18310. this.vectors.push(this.maximum.clone());
  18311. this.vectors.push(this.minimum.clone());
  18312. this.vectors[2].x = this.maximum.x;
  18313. this.vectors.push(this.minimum.clone());
  18314. this.vectors[3].y = this.maximum.y;
  18315. this.vectors.push(this.minimum.clone());
  18316. this.vectors[4].z = this.maximum.z;
  18317. this.vectors.push(this.maximum.clone());
  18318. this.vectors[5].z = this.minimum.z;
  18319. this.vectors.push(this.maximum.clone());
  18320. this.vectors[6].x = this.minimum.x;
  18321. this.vectors.push(this.maximum.clone());
  18322. this.vectors[7].y = this.minimum.y;
  18323. // OBB
  18324. this.center = this.maximum.add(this.minimum).scale(0.5);
  18325. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18326. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18327. // World
  18328. for (var index = 0; index < this.vectors.length; index++) {
  18329. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18330. }
  18331. this.minimumWorld = BABYLON.Vector3.Zero();
  18332. this.maximumWorld = BABYLON.Vector3.Zero();
  18333. this.centerWorld = BABYLON.Vector3.Zero();
  18334. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18335. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18336. };
  18337. BoundingBox.prototype.getWorldMatrix = function () {
  18338. return this._worldMatrix;
  18339. };
  18340. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18341. this._worldMatrix.copyFrom(matrix);
  18342. return this;
  18343. };
  18344. BoundingBox.prototype._update = function (world) {
  18345. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18346. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18347. for (var index = 0; index < this.vectors.length; index++) {
  18348. var v = this.vectorsWorld[index];
  18349. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18350. if (v.x < this.minimumWorld.x)
  18351. this.minimumWorld.x = v.x;
  18352. if (v.y < this.minimumWorld.y)
  18353. this.minimumWorld.y = v.y;
  18354. if (v.z < this.minimumWorld.z)
  18355. this.minimumWorld.z = v.z;
  18356. if (v.x > this.maximumWorld.x)
  18357. this.maximumWorld.x = v.x;
  18358. if (v.y > this.maximumWorld.y)
  18359. this.maximumWorld.y = v.y;
  18360. if (v.z > this.maximumWorld.z)
  18361. this.maximumWorld.z = v.z;
  18362. }
  18363. // Extend
  18364. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18365. this.extendSizeWorld.scaleInPlace(0.5);
  18366. // OBB
  18367. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18368. this.centerWorld.scaleInPlace(0.5);
  18369. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18370. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18371. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18372. this._worldMatrix = world;
  18373. };
  18374. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18375. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18376. };
  18377. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18378. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18379. };
  18380. BoundingBox.prototype.intersectsPoint = function (point) {
  18381. var delta = -BABYLON.Epsilon;
  18382. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18383. return false;
  18384. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18385. return false;
  18386. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18387. return false;
  18388. return true;
  18389. };
  18390. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18391. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18392. };
  18393. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18394. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18395. return false;
  18396. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18397. return false;
  18398. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18399. return false;
  18400. return true;
  18401. };
  18402. // Statics
  18403. BoundingBox.Intersects = function (box0, box1) {
  18404. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18405. return false;
  18406. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18407. return false;
  18408. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18409. return false;
  18410. return true;
  18411. };
  18412. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18413. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18414. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18415. return (num <= (sphereRadius * sphereRadius));
  18416. };
  18417. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18418. for (var p = 0; p < 6; p++) {
  18419. for (var i = 0; i < 8; i++) {
  18420. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18421. return false;
  18422. }
  18423. }
  18424. }
  18425. return true;
  18426. };
  18427. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18428. for (var p = 0; p < 6; p++) {
  18429. var inCount = 8;
  18430. for (var i = 0; i < 8; i++) {
  18431. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18432. --inCount;
  18433. }
  18434. else {
  18435. break;
  18436. }
  18437. }
  18438. if (inCount === 0)
  18439. return false;
  18440. }
  18441. return true;
  18442. };
  18443. return BoundingBox;
  18444. }());
  18445. BABYLON.BoundingBox = BoundingBox;
  18446. })(BABYLON || (BABYLON = {}));
  18447. //# sourceMappingURL=babylon.boundingBox.js.map
  18448. var BABYLON;
  18449. (function (BABYLON) {
  18450. var computeBoxExtents = function (axis, box) {
  18451. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18452. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18453. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18454. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18455. var r = r0 + r1 + r2;
  18456. return {
  18457. min: p - r,
  18458. max: p + r
  18459. };
  18460. };
  18461. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18462. var axisOverlap = function (axis, box0, box1) {
  18463. var result0 = computeBoxExtents(axis, box0);
  18464. var result1 = computeBoxExtents(axis, box1);
  18465. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18466. };
  18467. var BoundingInfo = /** @class */ (function () {
  18468. function BoundingInfo(minimum, maximum) {
  18469. this.minimum = minimum;
  18470. this.maximum = maximum;
  18471. this._isLocked = false;
  18472. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18473. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18474. }
  18475. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18476. get: function () {
  18477. return this._isLocked;
  18478. },
  18479. set: function (value) {
  18480. this._isLocked = value;
  18481. },
  18482. enumerable: true,
  18483. configurable: true
  18484. });
  18485. // Methods
  18486. BoundingInfo.prototype.update = function (world) {
  18487. if (this._isLocked) {
  18488. return;
  18489. }
  18490. this.boundingBox._update(world);
  18491. this.boundingSphere._update(world);
  18492. };
  18493. /**
  18494. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18495. * @param center New center of the bounding info
  18496. * @param extend New extend of the bounding info
  18497. */
  18498. BoundingInfo.prototype.centerOn = function (center, extend) {
  18499. this.minimum = center.subtract(extend);
  18500. this.maximum = center.add(extend);
  18501. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18502. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18503. return this;
  18504. };
  18505. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18506. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18507. return false;
  18508. return this.boundingBox.isInFrustum(frustumPlanes);
  18509. };
  18510. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18511. /**
  18512. * Gets the world distance between the min and max points of the bounding box
  18513. */
  18514. get: function () {
  18515. var boundingBox = this.boundingBox;
  18516. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18517. return size.length();
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18523. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18524. };
  18525. BoundingInfo.prototype._checkCollision = function (collider) {
  18526. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18527. };
  18528. BoundingInfo.prototype.intersectsPoint = function (point) {
  18529. if (!this.boundingSphere.centerWorld) {
  18530. return false;
  18531. }
  18532. if (!this.boundingSphere.intersectsPoint(point)) {
  18533. return false;
  18534. }
  18535. if (!this.boundingBox.intersectsPoint(point)) {
  18536. return false;
  18537. }
  18538. return true;
  18539. };
  18540. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18541. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18542. return false;
  18543. }
  18544. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18545. return false;
  18546. }
  18547. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18548. return false;
  18549. }
  18550. if (!precise) {
  18551. return true;
  18552. }
  18553. var box0 = this.boundingBox;
  18554. var box1 = boundingInfo.boundingBox;
  18555. if (!axisOverlap(box0.directions[0], box0, box1))
  18556. return false;
  18557. if (!axisOverlap(box0.directions[1], box0, box1))
  18558. return false;
  18559. if (!axisOverlap(box0.directions[2], box0, box1))
  18560. return false;
  18561. if (!axisOverlap(box1.directions[0], box0, box1))
  18562. return false;
  18563. if (!axisOverlap(box1.directions[1], box0, box1))
  18564. return false;
  18565. if (!axisOverlap(box1.directions[2], box0, box1))
  18566. return false;
  18567. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18568. return false;
  18569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18570. return false;
  18571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18572. return false;
  18573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18574. return false;
  18575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18576. return false;
  18577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18578. return false;
  18579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18580. return false;
  18581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18582. return false;
  18583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18584. return false;
  18585. return true;
  18586. };
  18587. return BoundingInfo;
  18588. }());
  18589. BABYLON.BoundingInfo = BoundingInfo;
  18590. })(BABYLON || (BABYLON = {}));
  18591. //# sourceMappingURL=babylon.boundingInfo.js.map
  18592. var BABYLON;
  18593. (function (BABYLON) {
  18594. var TransformNode = /** @class */ (function (_super) {
  18595. __extends(TransformNode, _super);
  18596. function TransformNode(name, scene, isPure) {
  18597. if (scene === void 0) { scene = null; }
  18598. if (isPure === void 0) { isPure = true; }
  18599. var _this = _super.call(this, name, scene) || this;
  18600. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18601. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18602. _this._up = new BABYLON.Vector3(0, 1, 0);
  18603. _this._right = new BABYLON.Vector3(1, 0, 0);
  18604. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18605. // Properties
  18606. _this._rotation = BABYLON.Vector3.Zero();
  18607. _this._scaling = BABYLON.Vector3.One();
  18608. _this._isDirty = false;
  18609. /**
  18610. * Set the billboard mode. Default is 0.
  18611. *
  18612. * | Value | Type | Description |
  18613. * | --- | --- | --- |
  18614. * | 0 | BILLBOARDMODE_NONE | |
  18615. * | 1 | BILLBOARDMODE_X | |
  18616. * | 2 | BILLBOARDMODE_Y | |
  18617. * | 4 | BILLBOARDMODE_Z | |
  18618. * | 7 | BILLBOARDMODE_ALL | |
  18619. *
  18620. */
  18621. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18622. _this.scalingDeterminant = 1;
  18623. _this.infiniteDistance = false;
  18624. /**
  18625. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18626. * By default the system will update normals to compensate
  18627. */
  18628. _this.ignoreNonUniformScaling = false;
  18629. _this.position = BABYLON.Vector3.Zero();
  18630. _this._localWorld = BABYLON.Matrix.Zero();
  18631. _this._worldMatrix = BABYLON.Matrix.Zero();
  18632. _this._worldMatrixDeterminant = 0;
  18633. _this._absolutePosition = BABYLON.Vector3.Zero();
  18634. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18635. _this._postMultiplyPivotMatrix = false;
  18636. _this._isWorldMatrixFrozen = false;
  18637. /**
  18638. * An event triggered after the world matrix is updated
  18639. */
  18640. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18641. _this._nonUniformScaling = false;
  18642. if (isPure) {
  18643. _this.getScene().addTransformNode(_this);
  18644. }
  18645. return _this;
  18646. }
  18647. /**
  18648. * Gets a string idenfifying the name of the class
  18649. * @returns "TransformNode" string
  18650. */
  18651. TransformNode.prototype.getClassName = function () {
  18652. return "TransformNode";
  18653. };
  18654. Object.defineProperty(TransformNode.prototype, "rotation", {
  18655. /**
  18656. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18657. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18658. * Default : (0.0, 0.0, 0.0)
  18659. */
  18660. get: function () {
  18661. return this._rotation;
  18662. },
  18663. set: function (newRotation) {
  18664. this._rotation = newRotation;
  18665. },
  18666. enumerable: true,
  18667. configurable: true
  18668. });
  18669. Object.defineProperty(TransformNode.prototype, "scaling", {
  18670. /**
  18671. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18672. * Default : (1.0, 1.0, 1.0)
  18673. */
  18674. get: function () {
  18675. return this._scaling;
  18676. },
  18677. /**
  18678. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18679. * Default : (1.0, 1.0, 1.0)
  18680. */
  18681. set: function (newScaling) {
  18682. this._scaling = newScaling;
  18683. },
  18684. enumerable: true,
  18685. configurable: true
  18686. });
  18687. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18688. /**
  18689. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18690. * It's null by default.
  18691. * 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)
  18692. */
  18693. get: function () {
  18694. return this._rotationQuaternion;
  18695. },
  18696. set: function (quaternion) {
  18697. this._rotationQuaternion = quaternion;
  18698. //reset the rotation vector.
  18699. if (quaternion && this.rotation.length()) {
  18700. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18701. }
  18702. },
  18703. enumerable: true,
  18704. configurable: true
  18705. });
  18706. Object.defineProperty(TransformNode.prototype, "forward", {
  18707. /**
  18708. * The forward direction of that transform in world space.
  18709. */
  18710. get: function () {
  18711. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. Object.defineProperty(TransformNode.prototype, "up", {
  18717. /**
  18718. * The up direction of that transform in world space.
  18719. */
  18720. get: function () {
  18721. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18722. },
  18723. enumerable: true,
  18724. configurable: true
  18725. });
  18726. Object.defineProperty(TransformNode.prototype, "right", {
  18727. /**
  18728. * The right direction of that transform in world space.
  18729. */
  18730. get: function () {
  18731. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. /**
  18737. * Returns the latest update of the World matrix
  18738. * Returns a Matrix.
  18739. */
  18740. TransformNode.prototype.getWorldMatrix = function () {
  18741. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18742. this.computeWorldMatrix();
  18743. }
  18744. return this._worldMatrix;
  18745. };
  18746. /** @hidden */
  18747. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18748. return this._worldMatrixDeterminant;
  18749. };
  18750. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18751. /**
  18752. * Returns directly the latest state of the mesh World matrix.
  18753. * A Matrix is returned.
  18754. */
  18755. get: function () {
  18756. return this._worldMatrix;
  18757. },
  18758. enumerable: true,
  18759. configurable: true
  18760. });
  18761. /**
  18762. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18763. * Returns the TransformNode.
  18764. */
  18765. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18766. this._poseMatrix.copyFrom(matrix);
  18767. return this;
  18768. };
  18769. /**
  18770. * Returns the mesh Pose matrix.
  18771. * Returned object : Matrix
  18772. */
  18773. TransformNode.prototype.getPoseMatrix = function () {
  18774. return this._poseMatrix;
  18775. };
  18776. TransformNode.prototype._isSynchronized = function () {
  18777. if (this._isDirty) {
  18778. return false;
  18779. }
  18780. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18781. return false;
  18782. if (this._cache.pivotMatrixUpdated) {
  18783. return false;
  18784. }
  18785. if (this.infiniteDistance) {
  18786. return false;
  18787. }
  18788. if (!this._cache.position.equals(this.position))
  18789. return false;
  18790. if (this.rotationQuaternion) {
  18791. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18792. return false;
  18793. }
  18794. if (!this._cache.rotation.equals(this.rotation))
  18795. return false;
  18796. if (!this._cache.scaling.equals(this.scaling))
  18797. return false;
  18798. return true;
  18799. };
  18800. TransformNode.prototype._initCache = function () {
  18801. _super.prototype._initCache.call(this);
  18802. this._cache.localMatrixUpdated = false;
  18803. this._cache.position = BABYLON.Vector3.Zero();
  18804. this._cache.scaling = BABYLON.Vector3.Zero();
  18805. this._cache.rotation = BABYLON.Vector3.Zero();
  18806. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18807. this._cache.billboardMode = -1;
  18808. };
  18809. TransformNode.prototype.markAsDirty = function (property) {
  18810. if (property === "rotation") {
  18811. this.rotationQuaternion = null;
  18812. }
  18813. this._currentRenderId = Number.MAX_VALUE;
  18814. this._isDirty = true;
  18815. return this;
  18816. };
  18817. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18818. /**
  18819. * Returns the current mesh absolute position.
  18820. * Retuns a Vector3.
  18821. */
  18822. get: function () {
  18823. return this._absolutePosition;
  18824. },
  18825. enumerable: true,
  18826. configurable: true
  18827. });
  18828. /**
  18829. * Sets a new matrix to apply before all other transformation
  18830. * @param matrix defines the transform matrix
  18831. * @returns the current TransformNode
  18832. */
  18833. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18834. return this.setPivotMatrix(matrix, false);
  18835. };
  18836. /**
  18837. * Sets a new pivot matrix to the current node
  18838. * @param matrix defines the new pivot matrix to use
  18839. * @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
  18840. * @returns the current TransformNode
  18841. */
  18842. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18843. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18844. this._pivotMatrix = matrix.clone();
  18845. this._cache.pivotMatrixUpdated = true;
  18846. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18847. if (this._postMultiplyPivotMatrix) {
  18848. if (!this._pivotMatrixInverse) {
  18849. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18850. }
  18851. else {
  18852. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18853. }
  18854. }
  18855. return this;
  18856. };
  18857. /**
  18858. * Returns the mesh pivot matrix.
  18859. * Default : Identity.
  18860. * A Matrix is returned.
  18861. */
  18862. TransformNode.prototype.getPivotMatrix = function () {
  18863. return this._pivotMatrix;
  18864. };
  18865. /**
  18866. * Prevents the World matrix to be computed any longer.
  18867. * Returns the TransformNode.
  18868. */
  18869. TransformNode.prototype.freezeWorldMatrix = function () {
  18870. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18871. this.computeWorldMatrix(true);
  18872. this._isWorldMatrixFrozen = true;
  18873. return this;
  18874. };
  18875. /**
  18876. * Allows back the World matrix computation.
  18877. * Returns the TransformNode.
  18878. */
  18879. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18880. this._isWorldMatrixFrozen = false;
  18881. this.computeWorldMatrix(true);
  18882. return this;
  18883. };
  18884. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18885. /**
  18886. * True if the World matrix has been frozen.
  18887. * Returns a boolean.
  18888. */
  18889. get: function () {
  18890. return this._isWorldMatrixFrozen;
  18891. },
  18892. enumerable: true,
  18893. configurable: true
  18894. });
  18895. /**
  18896. * Retuns the mesh absolute position in the World.
  18897. * Returns a Vector3.
  18898. */
  18899. TransformNode.prototype.getAbsolutePosition = function () {
  18900. this.computeWorldMatrix();
  18901. return this._absolutePosition;
  18902. };
  18903. /**
  18904. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18905. * Returns the TransformNode.
  18906. */
  18907. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18908. if (!absolutePosition) {
  18909. return this;
  18910. }
  18911. var absolutePositionX;
  18912. var absolutePositionY;
  18913. var absolutePositionZ;
  18914. if (absolutePosition.x === undefined) {
  18915. if (arguments.length < 3) {
  18916. return this;
  18917. }
  18918. absolutePositionX = arguments[0];
  18919. absolutePositionY = arguments[1];
  18920. absolutePositionZ = arguments[2];
  18921. }
  18922. else {
  18923. absolutePositionX = absolutePosition.x;
  18924. absolutePositionY = absolutePosition.y;
  18925. absolutePositionZ = absolutePosition.z;
  18926. }
  18927. if (this.parent) {
  18928. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18929. invertParentWorldMatrix.invert();
  18930. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18931. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18932. }
  18933. else {
  18934. this.position.x = absolutePositionX;
  18935. this.position.y = absolutePositionY;
  18936. this.position.z = absolutePositionZ;
  18937. }
  18938. return this;
  18939. };
  18940. /**
  18941. * Sets the mesh position in its local space.
  18942. * Returns the TransformNode.
  18943. */
  18944. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18945. this.computeWorldMatrix();
  18946. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18947. return this;
  18948. };
  18949. /**
  18950. * Returns the mesh position in the local space from the current World matrix values.
  18951. * Returns a new Vector3.
  18952. */
  18953. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18954. this.computeWorldMatrix();
  18955. var invLocalWorldMatrix = this._localWorld.clone();
  18956. invLocalWorldMatrix.invert();
  18957. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18958. };
  18959. /**
  18960. * Translates the mesh along the passed Vector3 in its local space.
  18961. * Returns the TransformNode.
  18962. */
  18963. TransformNode.prototype.locallyTranslate = function (vector3) {
  18964. this.computeWorldMatrix(true);
  18965. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18966. return this;
  18967. };
  18968. /**
  18969. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18970. * @param targetPoint the position (must be in same space as current mesh) to look at
  18971. * @param yawCor optional yaw (y-axis) correction in radians
  18972. * @param pitchCor optional pitch (x-axis) correction in radians
  18973. * @param rollCor optional roll (z-axis) correction in radians
  18974. * @param space the choosen space of the target
  18975. * @returns the TransformNode.
  18976. */
  18977. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18978. if (yawCor === void 0) { yawCor = 0; }
  18979. if (pitchCor === void 0) { pitchCor = 0; }
  18980. if (rollCor === void 0) { rollCor = 0; }
  18981. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18982. var dv = TransformNode._lookAtVectorCache;
  18983. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18984. targetPoint.subtractToRef(pos, dv);
  18985. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18986. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18987. var pitch = Math.atan2(dv.y, len);
  18988. if (this.rotationQuaternion) {
  18989. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18990. }
  18991. else {
  18992. this.rotation.x = pitch + pitchCor;
  18993. this.rotation.y = yaw + yawCor;
  18994. this.rotation.z = rollCor;
  18995. }
  18996. return this;
  18997. };
  18998. /**
  18999. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19000. * This Vector3 is expressed in the World space.
  19001. */
  19002. TransformNode.prototype.getDirection = function (localAxis) {
  19003. var result = BABYLON.Vector3.Zero();
  19004. this.getDirectionToRef(localAxis, result);
  19005. return result;
  19006. };
  19007. /**
  19008. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19009. * localAxis is expressed in the mesh local space.
  19010. * result is computed in the Wordl space from the mesh World matrix.
  19011. * Returns the TransformNode.
  19012. */
  19013. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19014. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19015. return this;
  19016. };
  19017. /**
  19018. * Sets a new pivot point to the current node
  19019. * @param point defines the new pivot point to use
  19020. * @param space defines if the point is in world or local space (local by default)
  19021. * @returns the current TransformNode
  19022. */
  19023. TransformNode.prototype.setPivotPoint = function (point, space) {
  19024. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19025. if (this.getScene().getRenderId() == 0) {
  19026. this.computeWorldMatrix(true);
  19027. }
  19028. var wm = this.getWorldMatrix();
  19029. if (space == BABYLON.Space.WORLD) {
  19030. var tmat = BABYLON.Tmp.Matrix[0];
  19031. wm.invertToRef(tmat);
  19032. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19033. }
  19034. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19035. };
  19036. /**
  19037. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19038. */
  19039. TransformNode.prototype.getPivotPoint = function () {
  19040. var point = BABYLON.Vector3.Zero();
  19041. this.getPivotPointToRef(point);
  19042. return point;
  19043. };
  19044. /**
  19045. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19046. * Returns the TransformNode.
  19047. */
  19048. TransformNode.prototype.getPivotPointToRef = function (result) {
  19049. result.x = -this._pivotMatrix.m[12];
  19050. result.y = -this._pivotMatrix.m[13];
  19051. result.z = -this._pivotMatrix.m[14];
  19052. return this;
  19053. };
  19054. /**
  19055. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19056. */
  19057. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19058. var point = BABYLON.Vector3.Zero();
  19059. this.getAbsolutePivotPointToRef(point);
  19060. return point;
  19061. };
  19062. /**
  19063. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19064. * Returns the TransformNode.
  19065. */
  19066. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19067. result.x = this._pivotMatrix.m[12];
  19068. result.y = this._pivotMatrix.m[13];
  19069. result.z = this._pivotMatrix.m[14];
  19070. this.getPivotPointToRef(result);
  19071. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19072. return this;
  19073. };
  19074. /**
  19075. * Defines the passed node as the parent of the current node.
  19076. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19077. * Returns the TransformNode.
  19078. */
  19079. TransformNode.prototype.setParent = function (node) {
  19080. if (!node && !this.parent) {
  19081. return this;
  19082. }
  19083. if (!node) {
  19084. var rotation = BABYLON.Tmp.Quaternion[0];
  19085. var position = BABYLON.Tmp.Vector3[0];
  19086. var scale = BABYLON.Tmp.Vector3[1];
  19087. if (this.parent && this.parent.computeWorldMatrix) {
  19088. this.parent.computeWorldMatrix(true);
  19089. }
  19090. this.computeWorldMatrix(true);
  19091. this.getWorldMatrix().decompose(scale, rotation, position);
  19092. if (this.rotationQuaternion) {
  19093. this.rotationQuaternion.copyFrom(rotation);
  19094. }
  19095. else {
  19096. rotation.toEulerAnglesToRef(this.rotation);
  19097. }
  19098. this.scaling.x = scale.x;
  19099. this.scaling.y = scale.y;
  19100. this.scaling.z = scale.z;
  19101. this.position.x = position.x;
  19102. this.position.y = position.y;
  19103. this.position.z = position.z;
  19104. }
  19105. else {
  19106. var rotation = BABYLON.Tmp.Quaternion[0];
  19107. var position = BABYLON.Tmp.Vector3[0];
  19108. var scale = BABYLON.Tmp.Vector3[1];
  19109. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19110. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19111. this.computeWorldMatrix(true);
  19112. node.computeWorldMatrix(true);
  19113. node.getWorldMatrix().invertToRef(invParentMatrix);
  19114. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19115. diffMatrix.decompose(scale, rotation, position);
  19116. if (this.rotationQuaternion) {
  19117. this.rotationQuaternion.copyFrom(rotation);
  19118. }
  19119. else {
  19120. rotation.toEulerAnglesToRef(this.rotation);
  19121. }
  19122. this.position.x = position.x;
  19123. this.position.y = position.y;
  19124. this.position.z = position.z;
  19125. this.scaling.x = scale.x;
  19126. this.scaling.y = scale.y;
  19127. this.scaling.z = scale.z;
  19128. }
  19129. this.parent = node;
  19130. return this;
  19131. };
  19132. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19133. get: function () {
  19134. return this._nonUniformScaling;
  19135. },
  19136. enumerable: true,
  19137. configurable: true
  19138. });
  19139. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19140. if (this._nonUniformScaling === value) {
  19141. return false;
  19142. }
  19143. this._nonUniformScaling = value;
  19144. return true;
  19145. };
  19146. /**
  19147. * Attach the current TransformNode to another TransformNode associated with a bone
  19148. * @param bone Bone affecting the TransformNode
  19149. * @param affectedTransformNode TransformNode associated with the bone
  19150. */
  19151. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19152. this._transformToBoneReferal = affectedTransformNode;
  19153. this.parent = bone;
  19154. if (bone.getWorldMatrix().determinant() < 0) {
  19155. this.scalingDeterminant *= -1;
  19156. }
  19157. return this;
  19158. };
  19159. TransformNode.prototype.detachFromBone = function () {
  19160. if (!this.parent) {
  19161. return this;
  19162. }
  19163. if (this.parent.getWorldMatrix().determinant() < 0) {
  19164. this.scalingDeterminant *= -1;
  19165. }
  19166. this._transformToBoneReferal = null;
  19167. this.parent = null;
  19168. return this;
  19169. };
  19170. /**
  19171. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19172. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19173. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19174. * The passed axis is also normalized.
  19175. * Returns the TransformNode.
  19176. */
  19177. TransformNode.prototype.rotate = function (axis, amount, space) {
  19178. axis.normalize();
  19179. if (!this.rotationQuaternion) {
  19180. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19181. this.rotation = BABYLON.Vector3.Zero();
  19182. }
  19183. var rotationQuaternion;
  19184. if (!space || space === BABYLON.Space.LOCAL) {
  19185. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19186. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19187. }
  19188. else {
  19189. if (this.parent) {
  19190. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19191. invertParentWorldMatrix.invert();
  19192. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19193. }
  19194. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19195. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19196. }
  19197. return this;
  19198. };
  19199. /**
  19200. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19201. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19202. * The passed axis is also normalized.
  19203. * Returns the TransformNode.
  19204. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19205. */
  19206. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19207. axis.normalize();
  19208. if (!this.rotationQuaternion) {
  19209. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19210. this.rotation.copyFromFloats(0, 0, 0);
  19211. }
  19212. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19213. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19214. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19215. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19216. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19217. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19218. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19219. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19220. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19221. return this;
  19222. };
  19223. /**
  19224. * Translates the mesh along the axis vector for the passed distance in the given space.
  19225. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19226. * Returns the TransformNode.
  19227. */
  19228. TransformNode.prototype.translate = function (axis, distance, space) {
  19229. var displacementVector = axis.scale(distance);
  19230. if (!space || space === BABYLON.Space.LOCAL) {
  19231. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19232. this.setPositionWithLocalVector(tempV3);
  19233. }
  19234. else {
  19235. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19236. }
  19237. return this;
  19238. };
  19239. /**
  19240. * Adds a rotation step to the mesh current rotation.
  19241. * x, y, z are Euler angles expressed in radians.
  19242. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19243. * This means this rotation is made in the mesh local space only.
  19244. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19245. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19246. * ```javascript
  19247. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19248. * ```
  19249. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19250. * 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.
  19251. * Returns the TransformNode.
  19252. */
  19253. TransformNode.prototype.addRotation = function (x, y, z) {
  19254. var rotationQuaternion;
  19255. if (this.rotationQuaternion) {
  19256. rotationQuaternion = this.rotationQuaternion;
  19257. }
  19258. else {
  19259. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19260. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19261. }
  19262. var accumulation = BABYLON.Tmp.Quaternion[0];
  19263. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19264. rotationQuaternion.multiplyInPlace(accumulation);
  19265. if (!this.rotationQuaternion) {
  19266. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19267. }
  19268. return this;
  19269. };
  19270. /**
  19271. * Computes the mesh World matrix and returns it.
  19272. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19273. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19274. * If the parameter `force`is set to `true`, the actual computation is done.
  19275. * Returns the mesh World Matrix.
  19276. */
  19277. TransformNode.prototype.computeWorldMatrix = function (force) {
  19278. if (this._isWorldMatrixFrozen) {
  19279. return this._worldMatrix;
  19280. }
  19281. if (!force && this.isSynchronized(true)) {
  19282. this._currentRenderId = this.getScene().getRenderId();
  19283. return this._worldMatrix;
  19284. }
  19285. this._cache.position.copyFrom(this.position);
  19286. this._cache.scaling.copyFrom(this.scaling);
  19287. this._cache.pivotMatrixUpdated = false;
  19288. this._cache.billboardMode = this.billboardMode;
  19289. this._currentRenderId = this.getScene().getRenderId();
  19290. this._childRenderId = this.getScene().getRenderId();
  19291. this._isDirty = false;
  19292. // Scaling
  19293. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19294. // Rotation
  19295. //rotate, if quaternion is set and rotation was used
  19296. if (this.rotationQuaternion) {
  19297. var len = this.rotation.length();
  19298. if (len) {
  19299. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19300. this.rotation.copyFromFloats(0, 0, 0);
  19301. }
  19302. }
  19303. if (this.rotationQuaternion) {
  19304. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19305. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19306. }
  19307. else {
  19308. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19309. this._cache.rotation.copyFrom(this.rotation);
  19310. }
  19311. // Translation
  19312. var camera = this.getScene().activeCamera;
  19313. if (this.infiniteDistance && !this.parent && camera) {
  19314. var cameraWorldMatrix = camera.getWorldMatrix();
  19315. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19316. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19317. }
  19318. else {
  19319. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19320. }
  19321. // Composing transformations
  19322. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19323. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19324. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19325. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19326. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19327. // Need to decompose each rotation here
  19328. var currentPosition = BABYLON.Tmp.Vector3[3];
  19329. if (this.parent && this.parent.getWorldMatrix) {
  19330. if (this._transformToBoneReferal) {
  19331. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19332. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19333. }
  19334. else {
  19335. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19336. }
  19337. }
  19338. else {
  19339. currentPosition.copyFrom(this.position);
  19340. }
  19341. currentPosition.subtractInPlace(camera.globalPosition);
  19342. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19343. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19344. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19345. }
  19346. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19347. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19348. }
  19349. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19350. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19351. }
  19352. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19353. }
  19354. else {
  19355. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19356. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19357. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19358. }
  19359. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19360. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19361. }
  19362. // Local world
  19363. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19364. // Parent
  19365. if (this.parent && this.parent.getWorldMatrix) {
  19366. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19367. if (this._transformToBoneReferal) {
  19368. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19369. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19370. }
  19371. else {
  19372. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19373. }
  19374. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19375. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19376. this._worldMatrix.copyFrom(this._localWorld);
  19377. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19378. }
  19379. else {
  19380. if (this._transformToBoneReferal) {
  19381. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19382. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19383. }
  19384. else {
  19385. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19386. }
  19387. }
  19388. this._markSyncedWithParent();
  19389. }
  19390. else {
  19391. this._worldMatrix.copyFrom(this._localWorld);
  19392. }
  19393. // Post multiply inverse of pivotMatrix
  19394. if (this._postMultiplyPivotMatrix) {
  19395. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19396. }
  19397. // Normal matrix
  19398. if (!this.ignoreNonUniformScaling) {
  19399. if (this.scaling.isNonUniform) {
  19400. this._updateNonUniformScalingState(true);
  19401. }
  19402. else if (this.parent && this.parent._nonUniformScaling) {
  19403. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19404. }
  19405. else {
  19406. this._updateNonUniformScalingState(false);
  19407. }
  19408. }
  19409. else {
  19410. this._updateNonUniformScalingState(false);
  19411. }
  19412. this._afterComputeWorldMatrix();
  19413. // Absolute position
  19414. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19415. // Callbacks
  19416. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19417. if (!this._poseMatrix) {
  19418. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19419. }
  19420. // Cache the determinant
  19421. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19422. return this._worldMatrix;
  19423. };
  19424. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19425. };
  19426. /**
  19427. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19428. * @param func: callback function to add
  19429. *
  19430. * Returns the TransformNode.
  19431. */
  19432. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19433. this.onAfterWorldMatrixUpdateObservable.add(func);
  19434. return this;
  19435. };
  19436. /**
  19437. * Removes a registered callback function.
  19438. * Returns the TransformNode.
  19439. */
  19440. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19441. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19442. return this;
  19443. };
  19444. /**
  19445. * Clone the current transform node
  19446. * Returns the new transform node
  19447. * @param name Name of the new clone
  19448. * @param newParent New parent for the clone
  19449. * @param doNotCloneChildren Do not clone children hierarchy
  19450. */
  19451. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19452. var _this = this;
  19453. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19454. result.name = name;
  19455. result.id = name;
  19456. if (newParent) {
  19457. result.parent = newParent;
  19458. }
  19459. if (!doNotCloneChildren) {
  19460. // Children
  19461. var directDescendants = this.getDescendants(true);
  19462. for (var index = 0; index < directDescendants.length; index++) {
  19463. var child = directDescendants[index];
  19464. if (child.clone) {
  19465. child.clone(name + "." + child.name, result);
  19466. }
  19467. }
  19468. }
  19469. return result;
  19470. };
  19471. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19472. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19473. serializationObject.type = this.getClassName();
  19474. // Parent
  19475. if (this.parent) {
  19476. serializationObject.parentId = this.parent.id;
  19477. }
  19478. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19479. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19480. }
  19481. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19482. serializationObject.isEnabled = this.isEnabled();
  19483. // Parent
  19484. if (this.parent) {
  19485. serializationObject.parentId = this.parent.id;
  19486. }
  19487. return serializationObject;
  19488. };
  19489. // Statics
  19490. /**
  19491. * Returns a new TransformNode object parsed from the source provided.
  19492. * The parameter `parsedMesh` is the source.
  19493. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19494. */
  19495. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19496. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19497. if (BABYLON.Tags) {
  19498. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19499. }
  19500. if (parsedTransformNode.localMatrix) {
  19501. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19502. }
  19503. else if (parsedTransformNode.pivotMatrix) {
  19504. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19505. }
  19506. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19507. // Parent
  19508. if (parsedTransformNode.parentId) {
  19509. transformNode._waitingParentId = parsedTransformNode.parentId;
  19510. }
  19511. return transformNode;
  19512. };
  19513. /**
  19514. * Releases resources associated with this transform node.
  19515. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19516. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19517. */
  19518. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19519. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19520. // Animations
  19521. this.getScene().stopAnimation(this);
  19522. // Remove from scene
  19523. this.getScene().removeTransformNode(this);
  19524. this.onAfterWorldMatrixUpdateObservable.clear();
  19525. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19526. };
  19527. // Statics
  19528. TransformNode.BILLBOARDMODE_NONE = 0;
  19529. TransformNode.BILLBOARDMODE_X = 1;
  19530. TransformNode.BILLBOARDMODE_Y = 2;
  19531. TransformNode.BILLBOARDMODE_Z = 4;
  19532. TransformNode.BILLBOARDMODE_ALL = 7;
  19533. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19534. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19535. __decorate([
  19536. BABYLON.serializeAsVector3()
  19537. ], TransformNode.prototype, "_rotation", void 0);
  19538. __decorate([
  19539. BABYLON.serializeAsQuaternion()
  19540. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19541. __decorate([
  19542. BABYLON.serializeAsVector3()
  19543. ], TransformNode.prototype, "_scaling", void 0);
  19544. __decorate([
  19545. BABYLON.serialize()
  19546. ], TransformNode.prototype, "billboardMode", void 0);
  19547. __decorate([
  19548. BABYLON.serialize()
  19549. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19550. __decorate([
  19551. BABYLON.serialize()
  19552. ], TransformNode.prototype, "infiniteDistance", void 0);
  19553. __decorate([
  19554. BABYLON.serialize()
  19555. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19556. __decorate([
  19557. BABYLON.serializeAsVector3()
  19558. ], TransformNode.prototype, "position", void 0);
  19559. return TransformNode;
  19560. }(BABYLON.Node));
  19561. BABYLON.TransformNode = TransformNode;
  19562. })(BABYLON || (BABYLON = {}));
  19563. //# sourceMappingURL=babylon.transformNode.js.map
  19564. var BABYLON;
  19565. (function (BABYLON) {
  19566. /**
  19567. * Class used to store all common mesh properties
  19568. */
  19569. var AbstractMesh = /** @class */ (function (_super) {
  19570. __extends(AbstractMesh, _super);
  19571. // Constructor
  19572. /**
  19573. * Creates a new AbstractMesh
  19574. * @param name defines the name of the mesh
  19575. * @param scene defines the hosting scene
  19576. */
  19577. function AbstractMesh(name, scene) {
  19578. if (scene === void 0) { scene = null; }
  19579. var _this = _super.call(this, name, scene, false) || this;
  19580. _this._facetNb = 0; // facet number
  19581. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19582. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19583. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19584. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19585. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19586. _this._subDiv = {
  19587. max: 1,
  19588. X: 1,
  19589. Y: 1,
  19590. Z: 1
  19591. };
  19592. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19593. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19594. // Events
  19595. /**
  19596. * An event triggered when this mesh collides with another one
  19597. */
  19598. _this.onCollideObservable = new BABYLON.Observable();
  19599. /**
  19600. * An event triggered when the collision's position changes
  19601. */
  19602. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19603. /**
  19604. * An event triggered when material is changed
  19605. */
  19606. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19607. // Properties
  19608. /**
  19609. * Gets or sets the orientation for POV movement & rotation
  19610. */
  19611. _this.definedFacingForward = true;
  19612. /**
  19613. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19614. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19615. * * 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.
  19616. * @see http://doc.babylonjs.com/features/occlusionquery
  19617. */
  19618. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19619. /**
  19620. * 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:
  19621. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19622. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19623. * * 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.
  19624. * @see http://doc.babylonjs.com/features/occlusionquery
  19625. */
  19626. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19627. /**
  19628. * 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.
  19629. * The default value is -1 which means don't break the query and wait till the result
  19630. * @see http://doc.babylonjs.com/features/occlusionquery
  19631. */
  19632. _this.occlusionRetryCount = -1;
  19633. _this._occlusionInternalRetryCounter = 0;
  19634. _this._isOccluded = false;
  19635. _this._isOcclusionQueryInProgress = false;
  19636. _this._visibility = 1.0;
  19637. /** Gets or sets the alpha index used to sort transparent meshes
  19638. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19639. */
  19640. _this.alphaIndex = Number.MAX_VALUE;
  19641. /**
  19642. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19643. */
  19644. _this.isVisible = true;
  19645. /**
  19646. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19647. */
  19648. _this.isPickable = true;
  19649. /**
  19650. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19651. */
  19652. _this.showBoundingBox = false;
  19653. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19654. _this.showSubMeshesBoundingBox = false;
  19655. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19656. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19657. */
  19658. _this.isBlocker = false;
  19659. /**
  19660. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19661. */
  19662. _this.enablePointerMoveEvents = false;
  19663. /**
  19664. * Specifies the rendering group id for this mesh (0 by default)
  19665. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19666. */
  19667. _this.renderingGroupId = 0;
  19668. _this._receiveShadows = false;
  19669. /**
  19670. * Gets or sets a boolean indicating if the outline must be rendered as well
  19671. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19672. */
  19673. _this.renderOutline = false;
  19674. /** Defines color to use when rendering outline */
  19675. _this.outlineColor = BABYLON.Color3.Red();
  19676. /** Define width to use when rendering outline */
  19677. _this.outlineWidth = 0.02;
  19678. /**
  19679. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19680. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19681. */
  19682. _this.renderOverlay = false;
  19683. /** Defines color to use when rendering overlay */
  19684. _this.overlayColor = BABYLON.Color3.Red();
  19685. /** Defines alpha to use when rendering overlay */
  19686. _this.overlayAlpha = 0.5;
  19687. _this._hasVertexAlpha = false;
  19688. _this._useVertexColors = true;
  19689. _this._computeBonesUsingShaders = true;
  19690. _this._numBoneInfluencers = 4;
  19691. _this._applyFog = true;
  19692. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19693. _this.useOctreeForRenderingSelection = true;
  19694. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19695. _this.useOctreeForPicking = true;
  19696. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19697. _this.useOctreeForCollisions = true;
  19698. _this._layerMask = 0x0FFFFFFF;
  19699. /**
  19700. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19701. */
  19702. _this.alwaysSelectAsActiveMesh = false;
  19703. /**
  19704. * Gets or sets the current action manager
  19705. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19706. */
  19707. _this.actionManager = null;
  19708. /**
  19709. * Gets or sets impostor used for physic simulation
  19710. * @see http://doc.babylonjs.com/features/physics_engine
  19711. */
  19712. _this.physicsImpostor = null;
  19713. // Collisions
  19714. _this._checkCollisions = false;
  19715. _this._collisionMask = -1;
  19716. _this._collisionGroup = -1;
  19717. /**
  19718. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19719. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19720. */
  19721. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19722. /**
  19723. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19724. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19725. */
  19726. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19727. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19728. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19729. // Edges
  19730. /**
  19731. * Defines edge width used when edgesRenderer is enabled
  19732. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19733. */
  19734. _this.edgesWidth = 1;
  19735. /**
  19736. * Defines edge color used when edgesRenderer is enabled
  19737. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19738. */
  19739. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19740. // Cache
  19741. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19742. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19743. /** @hidden */
  19744. _this._renderId = 0;
  19745. /** @hidden */
  19746. _this._intersectionsInProgress = new Array();
  19747. /** @hidden */
  19748. _this._unIndexed = false;
  19749. /** @hidden */
  19750. _this._lightSources = new Array();
  19751. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19752. if (collidedMesh === void 0) { collidedMesh = null; }
  19753. //TODO move this to the collision coordinator!
  19754. if (_this.getScene().workerCollisions)
  19755. newPosition.multiplyInPlace(_this._collider._radius);
  19756. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19757. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19758. _this.position.addInPlace(_this._diffPositionForCollisions);
  19759. }
  19760. if (collidedMesh) {
  19761. _this.onCollideObservable.notifyObservers(collidedMesh);
  19762. }
  19763. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19764. };
  19765. _this.getScene().addMesh(_this);
  19766. _this._resyncLightSources();
  19767. return _this;
  19768. }
  19769. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19770. /**
  19771. * No billboard
  19772. */
  19773. get: function () {
  19774. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19780. /** Billboard on X axis */
  19781. get: function () {
  19782. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19783. },
  19784. enumerable: true,
  19785. configurable: true
  19786. });
  19787. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19788. /** Billboard on Y axis */
  19789. get: function () {
  19790. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19796. /** Billboard on Z axis */
  19797. get: function () {
  19798. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19804. /** Billboard on all axes */
  19805. get: function () {
  19806. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19812. /**
  19813. * Gets the number of facets in the mesh
  19814. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19815. */
  19816. get: function () {
  19817. return this._facetNb;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19823. /**
  19824. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19825. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19826. */
  19827. get: function () {
  19828. return this._partitioningSubdivisions;
  19829. },
  19830. set: function (nb) {
  19831. this._partitioningSubdivisions = nb;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19837. /**
  19838. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19839. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19840. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19841. */
  19842. get: function () {
  19843. return this._partitioningBBoxRatio;
  19844. },
  19845. set: function (ratio) {
  19846. this._partitioningBBoxRatio = ratio;
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19852. /**
  19853. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19854. * Works only for updatable meshes.
  19855. * Doesn't work with multi-materials
  19856. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19857. */
  19858. get: function () {
  19859. return this._facetDepthSort;
  19860. },
  19861. set: function (sort) {
  19862. this._facetDepthSort = sort;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19868. /**
  19869. * The location (Vector3) where the facet depth sort must be computed from.
  19870. * By default, the active camera position.
  19871. * Used only when facet depth sort is enabled
  19872. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19873. */
  19874. get: function () {
  19875. return this._facetDepthSortFrom;
  19876. },
  19877. set: function (location) {
  19878. this._facetDepthSortFrom = location;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19884. /**
  19885. * gets a boolean indicating if facetData is enabled
  19886. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19887. */
  19888. get: function () {
  19889. return this._facetDataEnabled;
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. /** @hidden */
  19895. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19896. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19897. return false;
  19898. }
  19899. this._markSubMeshesAsMiscDirty();
  19900. return true;
  19901. };
  19902. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19903. /** Set a function to call when this mesh collides with another one */
  19904. set: function (callback) {
  19905. if (this._onCollideObserver) {
  19906. this.onCollideObservable.remove(this._onCollideObserver);
  19907. }
  19908. this._onCollideObserver = this.onCollideObservable.add(callback);
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19914. /** Set a function to call when the collision's position changes */
  19915. set: function (callback) {
  19916. if (this._onCollisionPositionChangeObserver) {
  19917. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19918. }
  19919. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19920. },
  19921. enumerable: true,
  19922. configurable: true
  19923. });
  19924. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19925. /**
  19926. * 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
  19927. * @see http://doc.babylonjs.com/features/occlusionquery
  19928. */
  19929. get: function () {
  19930. return this._isOccluded;
  19931. },
  19932. set: function (value) {
  19933. this._isOccluded = value;
  19934. },
  19935. enumerable: true,
  19936. configurable: true
  19937. });
  19938. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19939. /**
  19940. * Flag to check the progress status of the query
  19941. * @see http://doc.babylonjs.com/features/occlusionquery
  19942. */
  19943. get: function () {
  19944. return this._isOcclusionQueryInProgress;
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19950. /**
  19951. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19952. */
  19953. get: function () {
  19954. return this._visibility;
  19955. },
  19956. /**
  19957. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19958. */
  19959. set: function (value) {
  19960. if (this._visibility === value) {
  19961. return;
  19962. }
  19963. this._visibility = value;
  19964. this._markSubMeshesAsMiscDirty();
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Object.defineProperty(AbstractMesh.prototype, "material", {
  19970. /** Gets or sets current material */
  19971. get: function () {
  19972. return this._material;
  19973. },
  19974. set: function (value) {
  19975. if (this._material === value) {
  19976. return;
  19977. }
  19978. this._material = value;
  19979. if (this.onMaterialChangedObservable.hasObservers) {
  19980. this.onMaterialChangedObservable.notifyObservers(this);
  19981. }
  19982. if (!this.subMeshes) {
  19983. return;
  19984. }
  19985. this._unBindEffect();
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19991. /**
  19992. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19993. * @see http://doc.babylonjs.com/babylon101/shadows
  19994. */
  19995. get: function () {
  19996. return this._receiveShadows;
  19997. },
  19998. set: function (value) {
  19999. if (this._receiveShadows === value) {
  20000. return;
  20001. }
  20002. this._receiveShadows = value;
  20003. this._markSubMeshesAsLightDirty();
  20004. },
  20005. enumerable: true,
  20006. configurable: true
  20007. });
  20008. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20009. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20010. get: function () {
  20011. return this._hasVertexAlpha;
  20012. },
  20013. set: function (value) {
  20014. if (this._hasVertexAlpha === value) {
  20015. return;
  20016. }
  20017. this._hasVertexAlpha = value;
  20018. this._markSubMeshesAsAttributesDirty();
  20019. this._markSubMeshesAsMiscDirty();
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20025. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20026. get: function () {
  20027. return this._useVertexColors;
  20028. },
  20029. set: function (value) {
  20030. if (this._useVertexColors === value) {
  20031. return;
  20032. }
  20033. this._useVertexColors = value;
  20034. this._markSubMeshesAsAttributesDirty();
  20035. },
  20036. enumerable: true,
  20037. configurable: true
  20038. });
  20039. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20040. /**
  20041. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20042. */
  20043. get: function () {
  20044. return this._computeBonesUsingShaders;
  20045. },
  20046. set: function (value) {
  20047. if (this._computeBonesUsingShaders === value) {
  20048. return;
  20049. }
  20050. this._computeBonesUsingShaders = value;
  20051. this._markSubMeshesAsAttributesDirty();
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20057. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20058. get: function () {
  20059. return this._numBoneInfluencers;
  20060. },
  20061. set: function (value) {
  20062. if (this._numBoneInfluencers === value) {
  20063. return;
  20064. }
  20065. this._numBoneInfluencers = value;
  20066. this._markSubMeshesAsAttributesDirty();
  20067. },
  20068. enumerable: true,
  20069. configurable: true
  20070. });
  20071. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20072. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20073. get: function () {
  20074. return this._applyFog;
  20075. },
  20076. set: function (value) {
  20077. if (this._applyFog === value) {
  20078. return;
  20079. }
  20080. this._applyFog = value;
  20081. this._markSubMeshesAsMiscDirty();
  20082. },
  20083. enumerable: true,
  20084. configurable: true
  20085. });
  20086. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20087. /**
  20088. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20089. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20090. */
  20091. get: function () {
  20092. return this._layerMask;
  20093. },
  20094. set: function (value) {
  20095. if (value === this._layerMask) {
  20096. return;
  20097. }
  20098. this._layerMask = value;
  20099. this._resyncLightSources();
  20100. },
  20101. enumerable: true,
  20102. configurable: true
  20103. });
  20104. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20105. /**
  20106. * Gets or sets a collision mask used to mask collisions (default is -1).
  20107. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20108. */
  20109. get: function () {
  20110. return this._collisionMask;
  20111. },
  20112. set: function (mask) {
  20113. this._collisionMask = !isNaN(mask) ? mask : -1;
  20114. },
  20115. enumerable: true,
  20116. configurable: true
  20117. });
  20118. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20119. /**
  20120. * Gets or sets the current collision group mask (-1 by default).
  20121. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20122. */
  20123. get: function () {
  20124. return this._collisionGroup;
  20125. },
  20126. set: function (mask) {
  20127. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20128. },
  20129. enumerable: true,
  20130. configurable: true
  20131. });
  20132. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20133. /** @hidden */
  20134. get: function () {
  20135. return null;
  20136. },
  20137. enumerable: true,
  20138. configurable: true
  20139. });
  20140. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20141. get: function () {
  20142. return this._skeleton;
  20143. },
  20144. /**
  20145. * Gets or sets a skeleton to apply skining transformations
  20146. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20147. */
  20148. set: function (value) {
  20149. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20150. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20151. }
  20152. if (value && value.needInitialSkinMatrix) {
  20153. value._registerMeshWithPoseMatrix(this);
  20154. }
  20155. this._skeleton = value;
  20156. if (!this._skeleton) {
  20157. this._bonesTransformMatrices = null;
  20158. }
  20159. this._markSubMeshesAsAttributesDirty();
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. /**
  20165. * Returns the string "AbstractMesh"
  20166. * @returns "AbstractMesh"
  20167. */
  20168. AbstractMesh.prototype.getClassName = function () {
  20169. return "AbstractMesh";
  20170. };
  20171. /**
  20172. * Gets a string representation of the current mesh
  20173. * @param fullDetails defines a boolean indicating if full details must be included
  20174. * @returns a string representation of the current mesh
  20175. */
  20176. AbstractMesh.prototype.toString = function (fullDetails) {
  20177. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20178. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20179. if (this._skeleton) {
  20180. ret += ", skeleton: " + this._skeleton.name;
  20181. }
  20182. if (fullDetails) {
  20183. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20184. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20185. }
  20186. return ret;
  20187. };
  20188. /** @hidden */
  20189. AbstractMesh.prototype._rebuild = function () {
  20190. if (this._occlusionQuery) {
  20191. this._occlusionQuery = null;
  20192. }
  20193. if (this._edgesRenderer) {
  20194. this._edgesRenderer._rebuild();
  20195. }
  20196. if (!this.subMeshes) {
  20197. return;
  20198. }
  20199. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20200. var subMesh = _a[_i];
  20201. subMesh._rebuild();
  20202. }
  20203. };
  20204. /** @hidden */
  20205. AbstractMesh.prototype._resyncLightSources = function () {
  20206. this._lightSources.length = 0;
  20207. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20208. var light = _a[_i];
  20209. if (!light.isEnabled()) {
  20210. continue;
  20211. }
  20212. if (light.canAffectMesh(this)) {
  20213. this._lightSources.push(light);
  20214. }
  20215. }
  20216. this._markSubMeshesAsLightDirty();
  20217. };
  20218. /** @hidden */
  20219. AbstractMesh.prototype._resyncLighSource = function (light) {
  20220. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20221. var index = this._lightSources.indexOf(light);
  20222. if (index === -1) {
  20223. if (!isIn) {
  20224. return;
  20225. }
  20226. this._lightSources.push(light);
  20227. }
  20228. else {
  20229. if (isIn) {
  20230. return;
  20231. }
  20232. this._lightSources.splice(index, 1);
  20233. }
  20234. this._markSubMeshesAsLightDirty();
  20235. };
  20236. /** @hidden */
  20237. AbstractMesh.prototype._unBindEffect = function () {
  20238. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20239. var subMesh = _a[_i];
  20240. subMesh.setEffect(null);
  20241. }
  20242. };
  20243. /** @hidden */
  20244. AbstractMesh.prototype._removeLightSource = function (light) {
  20245. var index = this._lightSources.indexOf(light);
  20246. if (index === -1) {
  20247. return;
  20248. }
  20249. this._lightSources.splice(index, 1);
  20250. this._markSubMeshesAsLightDirty();
  20251. };
  20252. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20253. if (!this.subMeshes) {
  20254. return;
  20255. }
  20256. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20257. var subMesh = _a[_i];
  20258. if (subMesh._materialDefines) {
  20259. func(subMesh._materialDefines);
  20260. }
  20261. }
  20262. };
  20263. /** @hidden */
  20264. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20265. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20266. };
  20267. /** @hidden */
  20268. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20269. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20270. };
  20271. /** @hidden */
  20272. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20273. if (!this.subMeshes) {
  20274. return;
  20275. }
  20276. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20277. var subMesh = _a[_i];
  20278. var material = subMesh.getMaterial();
  20279. if (material) {
  20280. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20281. }
  20282. }
  20283. };
  20284. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20285. /**
  20286. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20287. */
  20288. get: function () {
  20289. return this._scaling;
  20290. },
  20291. set: function (newScaling) {
  20292. this._scaling = newScaling;
  20293. if (this.physicsImpostor) {
  20294. this.physicsImpostor.forceUpdate();
  20295. }
  20296. },
  20297. enumerable: true,
  20298. configurable: true
  20299. });
  20300. // Methods
  20301. /**
  20302. * Disables the mesh edge rendering mode
  20303. * @returns the currentAbstractMesh
  20304. */
  20305. AbstractMesh.prototype.disableEdgesRendering = function () {
  20306. if (this._edgesRenderer) {
  20307. this._edgesRenderer.dispose();
  20308. this._edgesRenderer = null;
  20309. }
  20310. return this;
  20311. };
  20312. /**
  20313. * Enables the edge rendering mode on the mesh.
  20314. * This mode makes the mesh edges visible
  20315. * @param epsilon defines the maximal distance between two angles to detect a face
  20316. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20317. * @returns the currentAbstractMesh
  20318. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20319. */
  20320. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20321. if (epsilon === void 0) { epsilon = 0.95; }
  20322. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20323. this.disableEdgesRendering();
  20324. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20325. return this;
  20326. };
  20327. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20328. /**
  20329. * Gets the edgesRenderer associated with the mesh
  20330. */
  20331. get: function () {
  20332. return this._edgesRenderer;
  20333. },
  20334. enumerable: true,
  20335. configurable: true
  20336. });
  20337. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20338. /**
  20339. * Returns true if the mesh is blocked. Implemented by child classes
  20340. */
  20341. get: function () {
  20342. return false;
  20343. },
  20344. enumerable: true,
  20345. configurable: true
  20346. });
  20347. /**
  20348. * Returns the mesh itself by default. Implemented by child classes
  20349. * @param camera defines the camera to use to pick the right LOD level
  20350. * @returns the currentAbstractMesh
  20351. */
  20352. AbstractMesh.prototype.getLOD = function (camera) {
  20353. return this;
  20354. };
  20355. /**
  20356. * Returns 0 by default. Implemented by child classes
  20357. * @returns an integer
  20358. */
  20359. AbstractMesh.prototype.getTotalVertices = function () {
  20360. return 0;
  20361. };
  20362. /**
  20363. * Returns null by default. Implemented by child classes
  20364. * @returns null
  20365. */
  20366. AbstractMesh.prototype.getIndices = function () {
  20367. return null;
  20368. };
  20369. /**
  20370. * Returns the array of the requested vertex data kind. Implemented by child classes
  20371. * @param kind defines the vertex data kind to use
  20372. * @returns null
  20373. */
  20374. AbstractMesh.prototype.getVerticesData = function (kind) {
  20375. return null;
  20376. };
  20377. /**
  20378. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20379. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20380. * Note that a new underlying VertexBuffer object is created each call.
  20381. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20382. * @param kind defines vertex data kind:
  20383. * * BABYLON.VertexBuffer.PositionKind
  20384. * * BABYLON.VertexBuffer.UVKind
  20385. * * BABYLON.VertexBuffer.UV2Kind
  20386. * * BABYLON.VertexBuffer.UV3Kind
  20387. * * BABYLON.VertexBuffer.UV4Kind
  20388. * * BABYLON.VertexBuffer.UV5Kind
  20389. * * BABYLON.VertexBuffer.UV6Kind
  20390. * * BABYLON.VertexBuffer.ColorKind
  20391. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20392. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20393. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20394. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20395. * @param data defines the data source
  20396. * @param updatable defines if the data must be flagged as updatable (or static)
  20397. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20398. * @returns the current mesh
  20399. */
  20400. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20401. return this;
  20402. };
  20403. /**
  20404. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20405. * If the mesh has no geometry, it is simply returned as it is.
  20406. * @param kind defines vertex data kind:
  20407. * * BABYLON.VertexBuffer.PositionKind
  20408. * * BABYLON.VertexBuffer.UVKind
  20409. * * BABYLON.VertexBuffer.UV2Kind
  20410. * * BABYLON.VertexBuffer.UV3Kind
  20411. * * BABYLON.VertexBuffer.UV4Kind
  20412. * * BABYLON.VertexBuffer.UV5Kind
  20413. * * BABYLON.VertexBuffer.UV6Kind
  20414. * * BABYLON.VertexBuffer.ColorKind
  20415. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20416. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20417. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20418. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20419. * @param data defines the data source
  20420. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20421. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20422. * @returns the current mesh
  20423. */
  20424. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20425. return this;
  20426. };
  20427. /**
  20428. * Sets the mesh indices,
  20429. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20430. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20431. * @param totalVertices Defines the total number of vertices
  20432. * @returns the current mesh
  20433. */
  20434. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20435. return this;
  20436. };
  20437. /**
  20438. * Gets a boolean indicating if specific vertex data is present
  20439. * @param kind defines the vertex data kind to use
  20440. * @returns true is data kind is present
  20441. */
  20442. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20443. return false;
  20444. };
  20445. /**
  20446. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20447. * @returns a BoundingInfo
  20448. */
  20449. AbstractMesh.prototype.getBoundingInfo = function () {
  20450. if (this._masterMesh) {
  20451. return this._masterMesh.getBoundingInfo();
  20452. }
  20453. if (!this._boundingInfo) {
  20454. // this._boundingInfo is being created here
  20455. this._updateBoundingInfo();
  20456. }
  20457. // cannot be null.
  20458. return this._boundingInfo;
  20459. };
  20460. /**
  20461. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20462. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20463. * @returns the current mesh
  20464. */
  20465. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20466. if (includeDescendants === void 0) { includeDescendants = true; }
  20467. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20468. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20469. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20470. if (maxDimension === 0) {
  20471. return this;
  20472. }
  20473. var scale = 1 / maxDimension;
  20474. this.scaling.scaleInPlace(scale);
  20475. return this;
  20476. };
  20477. /**
  20478. * Overwrite the current bounding info
  20479. * @param boundingInfo defines the new bounding info
  20480. * @returns the current mesh
  20481. */
  20482. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20483. this._boundingInfo = boundingInfo;
  20484. return this;
  20485. };
  20486. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20487. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20488. get: function () {
  20489. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20490. },
  20491. enumerable: true,
  20492. configurable: true
  20493. });
  20494. /** @hidden */
  20495. AbstractMesh.prototype._preActivate = function () {
  20496. };
  20497. /** @hidden */
  20498. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20499. };
  20500. /** @hidden */
  20501. AbstractMesh.prototype._activate = function (renderId) {
  20502. this._renderId = renderId;
  20503. };
  20504. /**
  20505. * Gets the current world matrix
  20506. * @returns a Matrix
  20507. */
  20508. AbstractMesh.prototype.getWorldMatrix = function () {
  20509. if (this._masterMesh) {
  20510. return this._masterMesh.getWorldMatrix();
  20511. }
  20512. return _super.prototype.getWorldMatrix.call(this);
  20513. };
  20514. /** @hidden */
  20515. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20516. if (this._masterMesh) {
  20517. return this._masterMesh._getWorldMatrixDeterminant();
  20518. }
  20519. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20520. };
  20521. // ================================== Point of View Movement =================================
  20522. /**
  20523. * Perform relative position change from the point of view of behind the front of the mesh.
  20524. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20525. * Supports definition of mesh facing forward or backward
  20526. * @param amountRight defines the distance on the right axis
  20527. * @param amountUp defines the distance on the up axis
  20528. * @param amountForward defines the distance on the forward axis
  20529. * @returns the current mesh
  20530. */
  20531. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20532. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20533. return this;
  20534. };
  20535. /**
  20536. * Calculate relative position change from the point of view of behind the front of the mesh.
  20537. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20538. * Supports definition of mesh facing forward or backward
  20539. * @param amountRight defines the distance on the right axis
  20540. * @param amountUp defines the distance on the up axis
  20541. * @param amountForward defines the distance on the forward axis
  20542. * @returns the new displacement vector
  20543. */
  20544. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20545. var rotMatrix = new BABYLON.Matrix();
  20546. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20547. rotQuaternion.toRotationMatrix(rotMatrix);
  20548. var translationDelta = BABYLON.Vector3.Zero();
  20549. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20550. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20551. return translationDelta;
  20552. };
  20553. // ================================== Point of View Rotation =================================
  20554. /**
  20555. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20556. * Supports definition of mesh facing forward or backward
  20557. * @param flipBack defines the flip
  20558. * @param twirlClockwise defines the twirl
  20559. * @param tiltRight defines the tilt
  20560. * @returns the current mesh
  20561. */
  20562. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20563. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20564. return this;
  20565. };
  20566. /**
  20567. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20568. * Supports definition of mesh facing forward or backward.
  20569. * @param flipBack defines the flip
  20570. * @param twirlClockwise defines the twirl
  20571. * @param tiltRight defines the tilt
  20572. * @returns the new rotation vector
  20573. */
  20574. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20575. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20576. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20577. };
  20578. /**
  20579. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20580. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20581. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20582. * @returns the new bounding vectors
  20583. */
  20584. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20585. if (includeDescendants === void 0) { includeDescendants = true; }
  20586. if (predicate === void 0) { predicate = null; }
  20587. // Ensures that all world matrix will be recomputed.
  20588. this.getScene().incrementRenderId();
  20589. this.computeWorldMatrix(true);
  20590. var min;
  20591. var max;
  20592. var boundingInfo = this.getBoundingInfo();
  20593. if (!this.subMeshes) {
  20594. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20595. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20596. }
  20597. else {
  20598. min = boundingInfo.boundingBox.minimumWorld;
  20599. max = boundingInfo.boundingBox.maximumWorld;
  20600. }
  20601. if (includeDescendants) {
  20602. var descendants = this.getDescendants(false);
  20603. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20604. var descendant = descendants_1[_i];
  20605. var childMesh = descendant;
  20606. childMesh.computeWorldMatrix(true);
  20607. // Filters meshes based on custom predicate function.
  20608. if (predicate && !predicate(childMesh)) {
  20609. continue;
  20610. }
  20611. //make sure we have the needed params to get mix and max
  20612. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20613. continue;
  20614. }
  20615. var childBoundingInfo = childMesh.getBoundingInfo();
  20616. var boundingBox = childBoundingInfo.boundingBox;
  20617. var minBox = boundingBox.minimumWorld;
  20618. var maxBox = boundingBox.maximumWorld;
  20619. BABYLON.Tools.CheckExtends(minBox, min, max);
  20620. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20621. }
  20622. }
  20623. return {
  20624. min: min,
  20625. max: max
  20626. };
  20627. };
  20628. /** @hidden */
  20629. AbstractMesh.prototype._updateBoundingInfo = function () {
  20630. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20631. this._boundingInfo.update(this.worldMatrixFromCache);
  20632. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20633. return this;
  20634. };
  20635. /** @hidden */
  20636. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20637. if (!this.subMeshes) {
  20638. return this;
  20639. }
  20640. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20641. var subMesh = this.subMeshes[subIndex];
  20642. if (!subMesh.IsGlobal) {
  20643. subMesh.updateBoundingInfo(matrix);
  20644. }
  20645. }
  20646. return this;
  20647. };
  20648. /** @hidden */
  20649. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20650. // Bounding info
  20651. this._updateBoundingInfo();
  20652. };
  20653. /**
  20654. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20655. * A mesh is in the frustum if its bounding box intersects the frustum
  20656. * @param frustumPlanes defines the frustum to test
  20657. * @returns true if the mesh is in the frustum planes
  20658. */
  20659. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20660. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20661. };
  20662. /**
  20663. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20664. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20665. * @param frustumPlanes defines the frustum to test
  20666. * @returns true if the mesh is completely in the frustum planes
  20667. */
  20668. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20669. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20670. };
  20671. /**
  20672. * True if the mesh intersects another mesh or a SolidParticle object
  20673. * @param mesh defines a target mesh or SolidParticle to test
  20674. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20675. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20676. * @returns true if there is an intersection
  20677. */
  20678. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20679. if (precise === void 0) { precise = false; }
  20680. if (!this._boundingInfo || !mesh._boundingInfo) {
  20681. return false;
  20682. }
  20683. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20684. return true;
  20685. }
  20686. if (includeDescendants) {
  20687. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20688. var child = _a[_i];
  20689. if (child.intersectsMesh(mesh, precise, true)) {
  20690. return true;
  20691. }
  20692. }
  20693. }
  20694. return false;
  20695. };
  20696. /**
  20697. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20698. * @param point defines the point to test
  20699. * @returns true if there is an intersection
  20700. */
  20701. AbstractMesh.prototype.intersectsPoint = function (point) {
  20702. if (!this._boundingInfo) {
  20703. return false;
  20704. }
  20705. return this._boundingInfo.intersectsPoint(point);
  20706. };
  20707. /**
  20708. * Gets the current physics impostor
  20709. * @see http://doc.babylonjs.com/features/physics_engine
  20710. * @returns a physics impostor or null
  20711. */
  20712. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20713. return this.physicsImpostor;
  20714. };
  20715. /**
  20716. * Gets the position of the current mesh in camera space
  20717. * @param camera defines the camera to use
  20718. * @returns a position
  20719. */
  20720. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20721. if (camera === void 0) { camera = null; }
  20722. if (!camera) {
  20723. camera = this.getScene().activeCamera;
  20724. }
  20725. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20726. };
  20727. /**
  20728. * Returns the distance from the mesh to the active camera
  20729. * @param camera defines the camera to use
  20730. * @returns the distance
  20731. */
  20732. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20733. if (camera === void 0) { camera = null; }
  20734. if (!camera) {
  20735. camera = this.getScene().activeCamera;
  20736. }
  20737. return this.absolutePosition.subtract(camera.position).length();
  20738. };
  20739. /**
  20740. * Apply a physic impulse to the mesh
  20741. * @param force defines the force to apply
  20742. * @param contactPoint defines where to apply the force
  20743. * @returns the current mesh
  20744. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20745. */
  20746. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20747. if (!this.physicsImpostor) {
  20748. return this;
  20749. }
  20750. this.physicsImpostor.applyImpulse(force, contactPoint);
  20751. return this;
  20752. };
  20753. /**
  20754. * Creates a physic joint between two meshes
  20755. * @param otherMesh defines the other mesh to use
  20756. * @param pivot1 defines the pivot to use on this mesh
  20757. * @param pivot2 defines the pivot to use on the other mesh
  20758. * @param options defines additional options (can be plugin dependent)
  20759. * @returns the current mesh
  20760. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20761. */
  20762. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20763. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20764. return this;
  20765. }
  20766. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20767. mainPivot: pivot1,
  20768. connectedPivot: pivot2,
  20769. nativeParams: options
  20770. });
  20771. return this;
  20772. };
  20773. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20774. // Collisions
  20775. /**
  20776. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20777. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20778. */
  20779. get: function () {
  20780. return this._checkCollisions;
  20781. },
  20782. set: function (collisionEnabled) {
  20783. this._checkCollisions = collisionEnabled;
  20784. if (this.getScene().workerCollisions) {
  20785. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20786. }
  20787. },
  20788. enumerable: true,
  20789. configurable: true
  20790. });
  20791. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20792. /**
  20793. * Gets Collider object used to compute collisions (not physics)
  20794. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20795. */
  20796. get: function () {
  20797. return this._collider;
  20798. },
  20799. enumerable: true,
  20800. configurable: true
  20801. });
  20802. /**
  20803. * Move the mesh using collision engine
  20804. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20805. * @param displacement defines the requested displacement vector
  20806. * @returns the current mesh
  20807. */
  20808. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20809. var globalPosition = this.getAbsolutePosition();
  20810. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20811. if (!this._collider) {
  20812. this._collider = new BABYLON.Collider();
  20813. }
  20814. this._collider._radius = this.ellipsoid;
  20815. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20816. return this;
  20817. };
  20818. // Submeshes octree
  20819. /**
  20820. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20821. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20822. * @param maxCapacity defines the maximum size of each block (64 by default)
  20823. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20824. * @returns the new octree
  20825. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20826. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20827. */
  20828. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20829. if (maxCapacity === void 0) { maxCapacity = 64; }
  20830. if (maxDepth === void 0) { maxDepth = 2; }
  20831. if (!this._submeshesOctree) {
  20832. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20833. }
  20834. this.computeWorldMatrix(true);
  20835. var boundingInfo = this.getBoundingInfo();
  20836. // Update octree
  20837. var bbox = boundingInfo.boundingBox;
  20838. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20839. return this._submeshesOctree;
  20840. };
  20841. // Collisions
  20842. /** @hidden */
  20843. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20844. this._generatePointsArray();
  20845. if (!this._positions) {
  20846. return this;
  20847. }
  20848. // Transformation
  20849. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20850. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20851. subMesh._lastColliderWorldVertices = [];
  20852. subMesh._trianglePlanes = [];
  20853. var start = subMesh.verticesStart;
  20854. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20855. for (var i = start; i < end; i++) {
  20856. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20857. }
  20858. }
  20859. // Collide
  20860. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20861. if (collider.collisionFound) {
  20862. collider.collidedMesh = this;
  20863. }
  20864. return this;
  20865. };
  20866. /** @hidden */
  20867. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20868. var subMeshes;
  20869. var len;
  20870. // Octrees
  20871. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20872. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20873. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20874. len = intersections.length;
  20875. subMeshes = intersections.data;
  20876. }
  20877. else {
  20878. subMeshes = this.subMeshes;
  20879. len = subMeshes.length;
  20880. }
  20881. for (var index = 0; index < len; index++) {
  20882. var subMesh = subMeshes[index];
  20883. // Bounding test
  20884. if (len > 1 && !subMesh._checkCollision(collider))
  20885. continue;
  20886. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20887. }
  20888. return this;
  20889. };
  20890. /** @hidden */
  20891. AbstractMesh.prototype._checkCollision = function (collider) {
  20892. // Bounding box test
  20893. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20894. return this;
  20895. // Transformation matrix
  20896. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20897. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20898. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20899. return this;
  20900. };
  20901. // Picking
  20902. /** @hidden */
  20903. AbstractMesh.prototype._generatePointsArray = function () {
  20904. return false;
  20905. };
  20906. /**
  20907. * Checks if the passed Ray intersects with the mesh
  20908. * @param ray defines the ray to use
  20909. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20910. * @returns the picking info
  20911. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20912. */
  20913. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20914. var pickingInfo = new BABYLON.PickingInfo();
  20915. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20916. return pickingInfo;
  20917. }
  20918. if (!this._generatePointsArray()) {
  20919. return pickingInfo;
  20920. }
  20921. var intersectInfo = null;
  20922. // Octrees
  20923. var subMeshes;
  20924. var len;
  20925. if (this._submeshesOctree && this.useOctreeForPicking) {
  20926. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20927. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20928. len = intersections.length;
  20929. subMeshes = intersections.data;
  20930. }
  20931. else {
  20932. subMeshes = this.subMeshes;
  20933. len = subMeshes.length;
  20934. }
  20935. for (var index = 0; index < len; index++) {
  20936. var subMesh = subMeshes[index];
  20937. // Bounding test
  20938. if (len > 1 && !subMesh.canIntersects(ray))
  20939. continue;
  20940. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20941. if (currentIntersectInfo) {
  20942. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20943. intersectInfo = currentIntersectInfo;
  20944. intersectInfo.subMeshId = index;
  20945. if (fastCheck) {
  20946. break;
  20947. }
  20948. }
  20949. }
  20950. }
  20951. if (intersectInfo) {
  20952. // Get picked point
  20953. var world = this.getWorldMatrix();
  20954. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20955. var direction = ray.direction.clone();
  20956. direction = direction.scale(intersectInfo.distance);
  20957. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20958. var pickedPoint = worldOrigin.add(worldDirection);
  20959. // Return result
  20960. pickingInfo.hit = true;
  20961. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20962. pickingInfo.pickedPoint = pickedPoint;
  20963. pickingInfo.pickedMesh = this;
  20964. pickingInfo.bu = intersectInfo.bu || 0;
  20965. pickingInfo.bv = intersectInfo.bv || 0;
  20966. pickingInfo.faceId = intersectInfo.faceId;
  20967. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20968. return pickingInfo;
  20969. }
  20970. return pickingInfo;
  20971. };
  20972. /**
  20973. * Clones the current mesh
  20974. * @param name defines the mesh name
  20975. * @param newParent defines the new mesh parent
  20976. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20977. * @returns the new mesh
  20978. */
  20979. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20980. return null;
  20981. };
  20982. /**
  20983. * Disposes all the submeshes of the current meshnp
  20984. * @returns the current mesh
  20985. */
  20986. AbstractMesh.prototype.releaseSubMeshes = function () {
  20987. if (this.subMeshes) {
  20988. while (this.subMeshes.length) {
  20989. this.subMeshes[0].dispose();
  20990. }
  20991. }
  20992. else {
  20993. this.subMeshes = new Array();
  20994. }
  20995. return this;
  20996. };
  20997. /**
  20998. * Releases resources associated with this abstract mesh.
  20999. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21000. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21001. */
  21002. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21003. var _this = this;
  21004. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21005. var index;
  21006. // Smart Array Retainers.
  21007. this.getScene().freeActiveMeshes();
  21008. this.getScene().freeRenderingGroups();
  21009. // Action manager
  21010. if (this.actionManager !== undefined && this.actionManager !== null) {
  21011. this.actionManager.dispose();
  21012. this.actionManager = null;
  21013. }
  21014. // Skeleton
  21015. this._skeleton = null;
  21016. // Physics
  21017. if (this.physicsImpostor) {
  21018. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21019. }
  21020. // Intersections in progress
  21021. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21022. var other = this._intersectionsInProgress[index];
  21023. var pos = other._intersectionsInProgress.indexOf(this);
  21024. other._intersectionsInProgress.splice(pos, 1);
  21025. }
  21026. this._intersectionsInProgress = [];
  21027. // Lights
  21028. var lights = this.getScene().lights;
  21029. lights.forEach(function (light) {
  21030. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21031. if (meshIndex !== -1) {
  21032. light.includedOnlyMeshes.splice(meshIndex, 1);
  21033. }
  21034. meshIndex = light.excludedMeshes.indexOf(_this);
  21035. if (meshIndex !== -1) {
  21036. light.excludedMeshes.splice(meshIndex, 1);
  21037. }
  21038. // Shadow generators
  21039. var generator = light.getShadowGenerator();
  21040. if (generator) {
  21041. var shadowMap = generator.getShadowMap();
  21042. if (shadowMap && shadowMap.renderList) {
  21043. meshIndex = shadowMap.renderList.indexOf(_this);
  21044. if (meshIndex !== -1) {
  21045. shadowMap.renderList.splice(meshIndex, 1);
  21046. }
  21047. }
  21048. }
  21049. });
  21050. // Edges
  21051. if (this._edgesRenderer) {
  21052. this._edgesRenderer.dispose();
  21053. this._edgesRenderer = null;
  21054. }
  21055. // SubMeshes
  21056. if (this.getClassName() !== "InstancedMesh") {
  21057. this.releaseSubMeshes();
  21058. }
  21059. // Octree
  21060. var sceneOctree = this.getScene().selectionOctree;
  21061. if (sceneOctree !== undefined && sceneOctree !== null) {
  21062. var index = sceneOctree.dynamicContent.indexOf(this);
  21063. if (index !== -1) {
  21064. sceneOctree.dynamicContent.splice(index, 1);
  21065. }
  21066. }
  21067. // Query
  21068. var engine = this.getScene().getEngine();
  21069. if (this._occlusionQuery) {
  21070. this._isOcclusionQueryInProgress = false;
  21071. engine.deleteQuery(this._occlusionQuery);
  21072. this._occlusionQuery = null;
  21073. }
  21074. // Engine
  21075. engine.wipeCaches();
  21076. // Remove from scene
  21077. this.getScene().removeMesh(this);
  21078. if (disposeMaterialAndTextures) {
  21079. if (this.material) {
  21080. this.material.dispose(false, true);
  21081. }
  21082. }
  21083. if (!doNotRecurse) {
  21084. // Particles
  21085. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21086. if (this.getScene().particleSystems[index].emitter === this) {
  21087. this.getScene().particleSystems[index].dispose();
  21088. index--;
  21089. }
  21090. }
  21091. }
  21092. // facet data
  21093. if (this._facetDataEnabled) {
  21094. this.disableFacetData();
  21095. }
  21096. this.onAfterWorldMatrixUpdateObservable.clear();
  21097. this.onCollideObservable.clear();
  21098. this.onCollisionPositionChangeObservable.clear();
  21099. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21100. };
  21101. /**
  21102. * Adds the passed mesh as a child to the current mesh
  21103. * @param mesh defines the child mesh
  21104. * @returns the current mesh
  21105. */
  21106. AbstractMesh.prototype.addChild = function (mesh) {
  21107. mesh.setParent(this);
  21108. return this;
  21109. };
  21110. /**
  21111. * Removes the passed mesh from the current mesh children list
  21112. * @param mesh defines the child mesh
  21113. * @returns the current mesh
  21114. */
  21115. AbstractMesh.prototype.removeChild = function (mesh) {
  21116. mesh.setParent(null);
  21117. return this;
  21118. };
  21119. // Facet data
  21120. /** @hidden */
  21121. AbstractMesh.prototype._initFacetData = function () {
  21122. if (!this._facetNormals) {
  21123. this._facetNormals = new Array();
  21124. }
  21125. if (!this._facetPositions) {
  21126. this._facetPositions = new Array();
  21127. }
  21128. if (!this._facetPartitioning) {
  21129. this._facetPartitioning = new Array();
  21130. }
  21131. this._facetNb = (this.getIndices().length / 3) | 0;
  21132. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21133. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21134. for (var f = 0; f < this._facetNb; f++) {
  21135. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21136. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21137. }
  21138. this._facetDataEnabled = true;
  21139. return this;
  21140. };
  21141. /**
  21142. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21143. * This method can be called within the render loop.
  21144. * 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
  21145. * @returns the current mesh
  21146. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21147. */
  21148. AbstractMesh.prototype.updateFacetData = function () {
  21149. if (!this._facetDataEnabled) {
  21150. this._initFacetData();
  21151. }
  21152. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21153. var indices = this.getIndices();
  21154. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21155. var bInfo = this.getBoundingInfo();
  21156. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21157. // init arrays, matrix and sort function on first call
  21158. this._facetDepthSortEnabled = true;
  21159. if (indices instanceof Uint16Array) {
  21160. this._depthSortedIndices = new Uint16Array(indices);
  21161. }
  21162. else if (indices instanceof Uint32Array) {
  21163. this._depthSortedIndices = new Uint32Array(indices);
  21164. }
  21165. else {
  21166. var needs32bits = false;
  21167. for (var i = 0; i < indices.length; i++) {
  21168. if (indices[i] > 65535) {
  21169. needs32bits = true;
  21170. break;
  21171. }
  21172. }
  21173. if (needs32bits) {
  21174. this._depthSortedIndices = new Uint32Array(indices);
  21175. }
  21176. else {
  21177. this._depthSortedIndices = new Uint16Array(indices);
  21178. }
  21179. }
  21180. this._facetDepthSortFunction = function (f1, f2) {
  21181. return (f2.sqDistance - f1.sqDistance);
  21182. };
  21183. if (!this._facetDepthSortFrom) {
  21184. var camera = this.getScene().activeCamera;
  21185. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21186. }
  21187. this._depthSortedFacets = [];
  21188. for (var f = 0; f < this._facetNb; f++) {
  21189. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21190. this._depthSortedFacets.push(depthSortedFacet);
  21191. }
  21192. this._invertedMatrix = BABYLON.Matrix.Identity();
  21193. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21194. }
  21195. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21196. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21197. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21198. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21199. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21200. this._subDiv.max = this._partitioningSubdivisions;
  21201. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21202. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21203. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21204. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21205. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21206. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21207. // set the parameters for ComputeNormals()
  21208. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21209. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21210. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21211. this._facetParameters.bInfo = bInfo;
  21212. this._facetParameters.bbSize = this._bbSize;
  21213. this._facetParameters.subDiv = this._subDiv;
  21214. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21215. this._facetParameters.depthSort = this._facetDepthSort;
  21216. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21217. this.computeWorldMatrix(true);
  21218. this._worldMatrix.invertToRef(this._invertedMatrix);
  21219. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21220. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21221. }
  21222. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21223. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21224. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21225. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21226. var l = (this._depthSortedIndices.length / 3) | 0;
  21227. for (var f = 0; f < l; f++) {
  21228. var sind = this._depthSortedFacets[f].ind;
  21229. this._depthSortedIndices[f * 3] = indices[sind];
  21230. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21231. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21232. }
  21233. this.updateIndices(this._depthSortedIndices);
  21234. }
  21235. return this;
  21236. };
  21237. /**
  21238. * Returns the facetLocalNormals array.
  21239. * The normals are expressed in the mesh local spac
  21240. * @returns an array of Vector3
  21241. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21242. */
  21243. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21244. if (!this._facetNormals) {
  21245. this.updateFacetData();
  21246. }
  21247. return this._facetNormals;
  21248. };
  21249. /**
  21250. * Returns the facetLocalPositions array.
  21251. * The facet positions are expressed in the mesh local space
  21252. * @returns an array of Vector3
  21253. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21254. */
  21255. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21256. if (!this._facetPositions) {
  21257. this.updateFacetData();
  21258. }
  21259. return this._facetPositions;
  21260. };
  21261. /**
  21262. * Returns the facetLocalPartioning array
  21263. * @returns an array of array of numbers
  21264. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21265. */
  21266. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21267. if (!this._facetPartitioning) {
  21268. this.updateFacetData();
  21269. }
  21270. return this._facetPartitioning;
  21271. };
  21272. /**
  21273. * Returns the i-th facet position in the world system.
  21274. * This method allocates a new Vector3 per call
  21275. * @param i defines the facet index
  21276. * @returns a new Vector3
  21277. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21278. */
  21279. AbstractMesh.prototype.getFacetPosition = function (i) {
  21280. var pos = BABYLON.Vector3.Zero();
  21281. this.getFacetPositionToRef(i, pos);
  21282. return pos;
  21283. };
  21284. /**
  21285. * Sets the reference Vector3 with the i-th facet position in the world system
  21286. * @param i defines the facet index
  21287. * @param ref defines the target vector
  21288. * @returns the current mesh
  21289. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21290. */
  21291. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21292. var localPos = (this.getFacetLocalPositions())[i];
  21293. var world = this.getWorldMatrix();
  21294. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21295. return this;
  21296. };
  21297. /**
  21298. * Returns the i-th facet normal in the world system.
  21299. * This method allocates a new Vector3 per call
  21300. * @param i defines the facet index
  21301. * @returns a new Vector3
  21302. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21303. */
  21304. AbstractMesh.prototype.getFacetNormal = function (i) {
  21305. var norm = BABYLON.Vector3.Zero();
  21306. this.getFacetNormalToRef(i, norm);
  21307. return norm;
  21308. };
  21309. /**
  21310. * Sets the reference Vector3 with the i-th facet normal in the world system
  21311. * @param i defines the facet index
  21312. * @param ref defines the target vector
  21313. * @returns the current mesh
  21314. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21315. */
  21316. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21317. var localNorm = (this.getFacetLocalNormals())[i];
  21318. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21319. return this;
  21320. };
  21321. /**
  21322. * 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)
  21323. * @param x defines x coordinate
  21324. * @param y defines y coordinate
  21325. * @param z defines z coordinate
  21326. * @returns the array of facet indexes
  21327. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21328. */
  21329. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21330. var bInfo = this.getBoundingInfo();
  21331. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21332. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21333. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21334. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21335. return null;
  21336. }
  21337. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21338. };
  21339. /**
  21340. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21341. * @param projected sets as the (x,y,z) world projection on the facet
  21342. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21343. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21344. * @param x defines x coordinate
  21345. * @param y defines y coordinate
  21346. * @param z defines z coordinate
  21347. * @returns the face index if found (or null instead)
  21348. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21349. */
  21350. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21351. if (checkFace === void 0) { checkFace = false; }
  21352. if (facing === void 0) { facing = true; }
  21353. var world = this.getWorldMatrix();
  21354. var invMat = BABYLON.Tmp.Matrix[5];
  21355. world.invertToRef(invMat);
  21356. var invVect = BABYLON.Tmp.Vector3[8];
  21357. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21358. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21359. if (projected) {
  21360. // tranform the local computed projected vector to world coordinates
  21361. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21362. }
  21363. return closest;
  21364. };
  21365. /**
  21366. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21367. * @param projected sets as the (x,y,z) local projection on the facet
  21368. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21369. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21370. * @param x defines x coordinate
  21371. * @param y defines y coordinate
  21372. * @param z defines z coordinate
  21373. * @returns the face index if found (or null instead)
  21374. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21375. */
  21376. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21377. if (checkFace === void 0) { checkFace = false; }
  21378. if (facing === void 0) { facing = true; }
  21379. var closest = null;
  21380. var tmpx = 0.0;
  21381. var tmpy = 0.0;
  21382. var tmpz = 0.0;
  21383. var d = 0.0; // tmp dot facet normal * facet position
  21384. var t0 = 0.0;
  21385. var projx = 0.0;
  21386. var projy = 0.0;
  21387. var projz = 0.0;
  21388. // Get all the facets in the same partitioning block than (x, y, z)
  21389. var facetPositions = this.getFacetLocalPositions();
  21390. var facetNormals = this.getFacetLocalNormals();
  21391. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21392. if (!facetsInBlock) {
  21393. return null;
  21394. }
  21395. // Get the closest facet to (x, y, z)
  21396. var shortest = Number.MAX_VALUE; // init distance vars
  21397. var tmpDistance = shortest;
  21398. var fib; // current facet in the block
  21399. var norm; // current facet normal
  21400. var p0; // current facet barycenter position
  21401. // loop on all the facets in the current partitioning block
  21402. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21403. fib = facetsInBlock[idx];
  21404. norm = facetNormals[fib];
  21405. p0 = facetPositions[fib];
  21406. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21407. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21408. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21409. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21410. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21411. projx = x + norm.x * t0;
  21412. projy = y + norm.y * t0;
  21413. projz = z + norm.z * t0;
  21414. tmpx = projx - x;
  21415. tmpy = projy - y;
  21416. tmpz = projz - z;
  21417. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21418. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21419. shortest = tmpDistance;
  21420. closest = fib;
  21421. if (projected) {
  21422. projected.x = projx;
  21423. projected.y = projy;
  21424. projected.z = projz;
  21425. }
  21426. }
  21427. }
  21428. }
  21429. return closest;
  21430. };
  21431. /**
  21432. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21433. * @returns the parameters
  21434. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21435. */
  21436. AbstractMesh.prototype.getFacetDataParameters = function () {
  21437. return this._facetParameters;
  21438. };
  21439. /**
  21440. * Disables the feature FacetData and frees the related memory
  21441. * @returns the current mesh
  21442. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21443. */
  21444. AbstractMesh.prototype.disableFacetData = function () {
  21445. if (this._facetDataEnabled) {
  21446. this._facetDataEnabled = false;
  21447. this._facetPositions = new Array();
  21448. this._facetNormals = new Array();
  21449. this._facetPartitioning = new Array();
  21450. this._facetParameters = null;
  21451. this._depthSortedIndices = new Uint32Array(0);
  21452. }
  21453. return this;
  21454. };
  21455. /**
  21456. * Updates the AbstractMesh indices array
  21457. * @param indices defines the data source
  21458. * @returns the current mesh
  21459. */
  21460. AbstractMesh.prototype.updateIndices = function (indices) {
  21461. return this;
  21462. };
  21463. /**
  21464. * Creates new normals data for the mesh
  21465. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21466. * @returns the current mesh
  21467. */
  21468. AbstractMesh.prototype.createNormals = function (updatable) {
  21469. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21470. var indices = this.getIndices();
  21471. var normals;
  21472. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21473. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21474. }
  21475. else {
  21476. normals = [];
  21477. }
  21478. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21479. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21480. return this;
  21481. };
  21482. /**
  21483. * Align the mesh with a normal
  21484. * @param normal defines the normal to use
  21485. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21486. * @returns the current mesh
  21487. */
  21488. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21489. if (!upDirection) {
  21490. upDirection = BABYLON.Axis.Y;
  21491. }
  21492. var axisX = BABYLON.Tmp.Vector3[0];
  21493. var axisZ = BABYLON.Tmp.Vector3[1];
  21494. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21495. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21496. if (this.rotationQuaternion) {
  21497. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21498. }
  21499. else {
  21500. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21501. }
  21502. return this;
  21503. };
  21504. /** @hidden */
  21505. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21506. var engine = this.getEngine();
  21507. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21508. this._isOccluded = false;
  21509. return;
  21510. }
  21511. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21512. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21513. if (isOcclusionQueryAvailable) {
  21514. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21515. this._isOcclusionQueryInProgress = false;
  21516. this._occlusionInternalRetryCounter = 0;
  21517. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21518. }
  21519. else {
  21520. this._occlusionInternalRetryCounter++;
  21521. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21522. this._isOcclusionQueryInProgress = false;
  21523. this._occlusionInternalRetryCounter = 0;
  21524. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21525. // if strict continue the last state of the object.
  21526. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21527. }
  21528. else {
  21529. return;
  21530. }
  21531. }
  21532. }
  21533. // Todo. Move into an occlusion query component.
  21534. var scene = this.getScene();
  21535. if (scene.getBoundingBoxRenderer) {
  21536. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21537. if (!this._occlusionQuery) {
  21538. this._occlusionQuery = engine.createQuery();
  21539. }
  21540. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21541. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21542. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21543. this._isOcclusionQueryInProgress = true;
  21544. }
  21545. };
  21546. /** No occlusion */
  21547. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21548. /** Occlusion set to optimisitic */
  21549. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21550. /** Occlusion set to strict */
  21551. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21552. /** Use an accurante occlusion algorithm */
  21553. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21554. /** Use a conservative occlusion algorithm */
  21555. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21556. return AbstractMesh;
  21557. }(BABYLON.TransformNode));
  21558. BABYLON.AbstractMesh = AbstractMesh;
  21559. })(BABYLON || (BABYLON = {}));
  21560. //# sourceMappingURL=babylon.abstractMesh.js.map
  21561. var BABYLON;
  21562. (function (BABYLON) {
  21563. /**
  21564. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21565. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21566. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  21567. */
  21568. var Light = /** @class */ (function (_super) {
  21569. __extends(Light, _super);
  21570. /**
  21571. * Creates a Light object in the scene.
  21572. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21573. * @param name The firendly name of the light
  21574. * @param scene The scene the light belongs too
  21575. */
  21576. function Light(name, scene) {
  21577. var _this = _super.call(this, name, scene) || this;
  21578. /**
  21579. * Diffuse gives the basic color to an object.
  21580. */
  21581. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21582. /**
  21583. * Specular produces a highlight color on an object.
  21584. * Note: This is note affecting PBR materials.
  21585. */
  21586. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21587. /**
  21588. * Strength of the light.
  21589. * Note: By default it is define in the framework own unit.
  21590. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21591. */
  21592. _this.intensity = 1.0;
  21593. /**
  21594. * Defines how far from the source the light is impacting in scene units.
  21595. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21596. */
  21597. _this.range = Number.MAX_VALUE;
  21598. /**
  21599. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21600. * of light.
  21601. */
  21602. _this._photometricScale = 1.0;
  21603. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21604. _this._radius = 0.00001;
  21605. /**
  21606. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21607. * exceeding the number allowed of the materials.
  21608. */
  21609. _this.renderPriority = 0;
  21610. _this._shadowEnabled = true;
  21611. _this._excludeWithLayerMask = 0;
  21612. _this._includeOnlyWithLayerMask = 0;
  21613. _this._lightmapMode = 0;
  21614. /**
  21615. * @hidden Internal use only.
  21616. */
  21617. _this._excludedMeshesIds = new Array();
  21618. /**
  21619. * @hidden Internal use only.
  21620. */
  21621. _this._includedOnlyMeshesIds = new Array();
  21622. _this.getScene().addLight(_this);
  21623. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21624. _this._buildUniformLayout();
  21625. _this.includedOnlyMeshes = new Array();
  21626. _this.excludedMeshes = new Array();
  21627. _this._resyncMeshes();
  21628. return _this;
  21629. }
  21630. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21631. /**
  21632. * If every light affecting the material is in this lightmapMode,
  21633. * material.lightmapTexture adds or multiplies
  21634. * (depends on material.useLightmapAsShadowmap)
  21635. * after every other light calculations.
  21636. */
  21637. get: function () {
  21638. return Light._LIGHTMAP_DEFAULT;
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21644. /**
  21645. * material.lightmapTexture as only diffuse lighting from this light
  21646. * adds only specular lighting from this light
  21647. * adds dynamic shadows
  21648. */
  21649. get: function () {
  21650. return Light._LIGHTMAP_SPECULAR;
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21656. /**
  21657. * material.lightmapTexture as only lighting
  21658. * no light calculation from this light
  21659. * only adds dynamic shadows from this light
  21660. */
  21661. get: function () {
  21662. return Light._LIGHTMAP_SHADOWSONLY;
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21668. /**
  21669. * Each light type uses the default quantity according to its type:
  21670. * point/spot lights use luminous intensity
  21671. * directional lights use illuminance
  21672. */
  21673. get: function () {
  21674. return Light._INTENSITYMODE_AUTOMATIC;
  21675. },
  21676. enumerable: true,
  21677. configurable: true
  21678. });
  21679. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21680. /**
  21681. * lumen (lm)
  21682. */
  21683. get: function () {
  21684. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21690. /**
  21691. * candela (lm/sr)
  21692. */
  21693. get: function () {
  21694. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21700. /**
  21701. * lux (lm/m^2)
  21702. */
  21703. get: function () {
  21704. return Light._INTENSITYMODE_ILLUMINANCE;
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21710. /**
  21711. * nit (cd/m^2)
  21712. */
  21713. get: function () {
  21714. return Light._INTENSITYMODE_LUMINANCE;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21720. /**
  21721. * Light type const id of the point light.
  21722. */
  21723. get: function () {
  21724. return Light._LIGHTTYPEID_POINTLIGHT;
  21725. },
  21726. enumerable: true,
  21727. configurable: true
  21728. });
  21729. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21730. /**
  21731. * Light type const id of the directional light.
  21732. */
  21733. get: function () {
  21734. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21735. },
  21736. enumerable: true,
  21737. configurable: true
  21738. });
  21739. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21740. /**
  21741. * Light type const id of the spot light.
  21742. */
  21743. get: function () {
  21744. return Light._LIGHTTYPEID_SPOTLIGHT;
  21745. },
  21746. enumerable: true,
  21747. configurable: true
  21748. });
  21749. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21750. /**
  21751. * Light type const id of the hemispheric light.
  21752. */
  21753. get: function () {
  21754. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Object.defineProperty(Light.prototype, "intensityMode", {
  21760. /**
  21761. * Gets the photometric scale used to interpret the intensity.
  21762. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21763. */
  21764. get: function () {
  21765. return this._intensityMode;
  21766. },
  21767. /**
  21768. * Sets the photometric scale used to interpret the intensity.
  21769. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21770. */
  21771. set: function (value) {
  21772. this._intensityMode = value;
  21773. this._computePhotometricScale();
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. ;
  21779. ;
  21780. Object.defineProperty(Light.prototype, "radius", {
  21781. /**
  21782. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21783. */
  21784. get: function () {
  21785. return this._radius;
  21786. },
  21787. /**
  21788. * sets the light radius used by PBR Materials to simulate soft area lights.
  21789. */
  21790. set: function (value) {
  21791. this._radius = value;
  21792. this._computePhotometricScale();
  21793. },
  21794. enumerable: true,
  21795. configurable: true
  21796. });
  21797. ;
  21798. ;
  21799. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21800. /**
  21801. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21802. * the current shadow generator.
  21803. */
  21804. get: function () {
  21805. return this._shadowEnabled;
  21806. },
  21807. /**
  21808. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21809. * the current shadow generator.
  21810. */
  21811. set: function (value) {
  21812. if (this._shadowEnabled === value) {
  21813. return;
  21814. }
  21815. this._shadowEnabled = value;
  21816. this._markMeshesAsLightDirty();
  21817. },
  21818. enumerable: true,
  21819. configurable: true
  21820. });
  21821. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21822. /**
  21823. * Gets the only meshes impacted by this light.
  21824. */
  21825. get: function () {
  21826. return this._includedOnlyMeshes;
  21827. },
  21828. /**
  21829. * Sets the only meshes impacted by this light.
  21830. */
  21831. set: function (value) {
  21832. this._includedOnlyMeshes = value;
  21833. this._hookArrayForIncludedOnly(value);
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21839. /**
  21840. * Gets the meshes not impacted by this light.
  21841. */
  21842. get: function () {
  21843. return this._excludedMeshes;
  21844. },
  21845. /**
  21846. * Sets the meshes not impacted by this light.
  21847. */
  21848. set: function (value) {
  21849. this._excludedMeshes = value;
  21850. this._hookArrayForExcluded(value);
  21851. },
  21852. enumerable: true,
  21853. configurable: true
  21854. });
  21855. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21856. /**
  21857. * Gets the layer id use to find what meshes are not impacted by the light.
  21858. * Inactive if 0
  21859. */
  21860. get: function () {
  21861. return this._excludeWithLayerMask;
  21862. },
  21863. /**
  21864. * Sets the layer id use to find what meshes are not impacted by the light.
  21865. * Inactive if 0
  21866. */
  21867. set: function (value) {
  21868. this._excludeWithLayerMask = value;
  21869. this._resyncMeshes();
  21870. },
  21871. enumerable: true,
  21872. configurable: true
  21873. });
  21874. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21875. /**
  21876. * Gets the layer id use to find what meshes are impacted by the light.
  21877. * Inactive if 0
  21878. */
  21879. get: function () {
  21880. return this._includeOnlyWithLayerMask;
  21881. },
  21882. /**
  21883. * Sets the layer id use to find what meshes are impacted by the light.
  21884. * Inactive if 0
  21885. */
  21886. set: function (value) {
  21887. this._includeOnlyWithLayerMask = value;
  21888. this._resyncMeshes();
  21889. },
  21890. enumerable: true,
  21891. configurable: true
  21892. });
  21893. Object.defineProperty(Light.prototype, "lightmapMode", {
  21894. /**
  21895. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21896. */
  21897. get: function () {
  21898. return this._lightmapMode;
  21899. },
  21900. /**
  21901. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21902. */
  21903. set: function (value) {
  21904. if (this._lightmapMode === value) {
  21905. return;
  21906. }
  21907. this._lightmapMode = value;
  21908. this._markMeshesAsLightDirty();
  21909. },
  21910. enumerable: true,
  21911. configurable: true
  21912. });
  21913. /**
  21914. * Returns the string "Light".
  21915. * @returns the class name
  21916. */
  21917. Light.prototype.getClassName = function () {
  21918. return "Light";
  21919. };
  21920. /**
  21921. * Converts the light information to a readable string for debug purpose.
  21922. * @param fullDetails Supports for multiple levels of logging within scene loading
  21923. * @returns the human readable light info
  21924. */
  21925. Light.prototype.toString = function (fullDetails) {
  21926. var ret = "Name: " + this.name;
  21927. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21928. if (this.animations) {
  21929. for (var i = 0; i < this.animations.length; i++) {
  21930. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21931. }
  21932. }
  21933. if (fullDetails) {
  21934. }
  21935. return ret;
  21936. };
  21937. /**
  21938. * Set the enabled state of this node.
  21939. * @param value - the new enabled state
  21940. */
  21941. Light.prototype.setEnabled = function (value) {
  21942. _super.prototype.setEnabled.call(this, value);
  21943. this._resyncMeshes();
  21944. };
  21945. /**
  21946. * Returns the Light associated shadow generator if any.
  21947. * @return the associated shadow generator.
  21948. */
  21949. Light.prototype.getShadowGenerator = function () {
  21950. return this._shadowGenerator;
  21951. };
  21952. /**
  21953. * Returns a Vector3, the absolute light position in the World.
  21954. * @returns the world space position of the light
  21955. */
  21956. Light.prototype.getAbsolutePosition = function () {
  21957. return BABYLON.Vector3.Zero();
  21958. };
  21959. /**
  21960. * Specifies if the light will affect the passed mesh.
  21961. * @param mesh The mesh to test against the light
  21962. * @return true the mesh is affected otherwise, false.
  21963. */
  21964. Light.prototype.canAffectMesh = function (mesh) {
  21965. if (!mesh) {
  21966. return true;
  21967. }
  21968. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21969. return false;
  21970. }
  21971. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21972. return false;
  21973. }
  21974. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21975. return false;
  21976. }
  21977. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21978. return false;
  21979. }
  21980. return true;
  21981. };
  21982. /**
  21983. * Computes and Returns the light World matrix.
  21984. * @returns the world matrix
  21985. */
  21986. Light.prototype.getWorldMatrix = function () {
  21987. this._currentRenderId = this.getScene().getRenderId();
  21988. this._childRenderId = this._currentRenderId;
  21989. var worldMatrix = this._getWorldMatrix();
  21990. if (this.parent && this.parent.getWorldMatrix) {
  21991. if (!this._parentedWorldMatrix) {
  21992. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21993. }
  21994. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21995. this._markSyncedWithParent();
  21996. return this._parentedWorldMatrix;
  21997. }
  21998. return worldMatrix;
  21999. };
  22000. /**
  22001. * Sort function to order lights for rendering.
  22002. * @param a First Light object to compare to second.
  22003. * @param b Second Light object to compare first.
  22004. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22005. */
  22006. Light.CompareLightsPriority = function (a, b) {
  22007. //shadow-casting lights have priority over non-shadow-casting lights
  22008. //the renderPrioirty is a secondary sort criterion
  22009. if (a.shadowEnabled !== b.shadowEnabled) {
  22010. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22011. }
  22012. return b.renderPriority - a.renderPriority;
  22013. };
  22014. /**
  22015. * Releases resources associated with this node.
  22016. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22017. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22018. */
  22019. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22020. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22021. if (this._shadowGenerator) {
  22022. this._shadowGenerator.dispose();
  22023. this._shadowGenerator = null;
  22024. }
  22025. // Animations
  22026. this.getScene().stopAnimation(this);
  22027. // Remove from meshes
  22028. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22029. var mesh = _a[_i];
  22030. mesh._removeLightSource(this);
  22031. }
  22032. this._uniformBuffer.dispose();
  22033. // Remove from scene
  22034. this.getScene().removeLight(this);
  22035. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22036. };
  22037. /**
  22038. * Returns the light type ID (integer).
  22039. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22040. */
  22041. Light.prototype.getTypeID = function () {
  22042. return 0;
  22043. };
  22044. /**
  22045. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22046. * @returns the scaled intensity in intensity mode unit
  22047. */
  22048. Light.prototype.getScaledIntensity = function () {
  22049. return this._photometricScale * this.intensity;
  22050. };
  22051. /**
  22052. * Returns a new Light object, named "name", from the current one.
  22053. * @param name The name of the cloned light
  22054. * @returns the new created light
  22055. */
  22056. Light.prototype.clone = function (name) {
  22057. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22058. if (!constructor) {
  22059. return null;
  22060. }
  22061. return BABYLON.SerializationHelper.Clone(constructor, this);
  22062. };
  22063. /**
  22064. * Serializes the current light into a Serialization object.
  22065. * @returns the serialized object.
  22066. */
  22067. Light.prototype.serialize = function () {
  22068. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22069. // Type
  22070. serializationObject.type = this.getTypeID();
  22071. // Parent
  22072. if (this.parent) {
  22073. serializationObject.parentId = this.parent.id;
  22074. }
  22075. // Inclusion / exclusions
  22076. if (this.excludedMeshes.length > 0) {
  22077. serializationObject.excludedMeshesIds = [];
  22078. this.excludedMeshes.forEach(function (mesh) {
  22079. serializationObject.excludedMeshesIds.push(mesh.id);
  22080. });
  22081. }
  22082. if (this.includedOnlyMeshes.length > 0) {
  22083. serializationObject.includedOnlyMeshesIds = [];
  22084. this.includedOnlyMeshes.forEach(function (mesh) {
  22085. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22086. });
  22087. }
  22088. // Animations
  22089. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22090. serializationObject.ranges = this.serializeAnimationRanges();
  22091. return serializationObject;
  22092. };
  22093. /**
  22094. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22095. * This new light is named "name" and added to the passed scene.
  22096. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22097. * @param name The friendly name of the light
  22098. * @param scene The scene the new light will belong to
  22099. * @returns the constructor function
  22100. */
  22101. Light.GetConstructorFromName = function (type, name, scene) {
  22102. switch (type) {
  22103. case 0:
  22104. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22105. case 1:
  22106. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22107. case 2:
  22108. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22109. case 3:
  22110. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22111. }
  22112. return null;
  22113. };
  22114. /**
  22115. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22116. * @param parsedLight The JSON representation of the light
  22117. * @param scene The scene to create the parsed light in
  22118. * @returns the created light after parsing
  22119. */
  22120. Light.Parse = function (parsedLight, scene) {
  22121. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22122. if (!constructor) {
  22123. return null;
  22124. }
  22125. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22126. // Inclusion / exclusions
  22127. if (parsedLight.excludedMeshesIds) {
  22128. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22129. }
  22130. if (parsedLight.includedOnlyMeshesIds) {
  22131. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22132. }
  22133. // Parent
  22134. if (parsedLight.parentId) {
  22135. light._waitingParentId = parsedLight.parentId;
  22136. }
  22137. // Animations
  22138. if (parsedLight.animations) {
  22139. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22140. var parsedAnimation = parsedLight.animations[animationIndex];
  22141. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22142. }
  22143. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22144. }
  22145. if (parsedLight.autoAnimate) {
  22146. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22147. }
  22148. return light;
  22149. };
  22150. Light.prototype._hookArrayForExcluded = function (array) {
  22151. var _this = this;
  22152. var oldPush = array.push;
  22153. array.push = function () {
  22154. var items = [];
  22155. for (var _i = 0; _i < arguments.length; _i++) {
  22156. items[_i] = arguments[_i];
  22157. }
  22158. var result = oldPush.apply(array, items);
  22159. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22160. var item = items_1[_a];
  22161. item._resyncLighSource(_this);
  22162. }
  22163. return result;
  22164. };
  22165. var oldSplice = array.splice;
  22166. array.splice = function (index, deleteCount) {
  22167. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22168. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22169. var item = deleted_1[_i];
  22170. item._resyncLighSource(_this);
  22171. }
  22172. return deleted;
  22173. };
  22174. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22175. var item = array_1[_i];
  22176. item._resyncLighSource(this);
  22177. }
  22178. };
  22179. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22180. var _this = this;
  22181. var oldPush = array.push;
  22182. array.push = function () {
  22183. var items = [];
  22184. for (var _i = 0; _i < arguments.length; _i++) {
  22185. items[_i] = arguments[_i];
  22186. }
  22187. var result = oldPush.apply(array, items);
  22188. _this._resyncMeshes();
  22189. return result;
  22190. };
  22191. var oldSplice = array.splice;
  22192. array.splice = function (index, deleteCount) {
  22193. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22194. _this._resyncMeshes();
  22195. return deleted;
  22196. };
  22197. this._resyncMeshes();
  22198. };
  22199. Light.prototype._resyncMeshes = function () {
  22200. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22201. var mesh = _a[_i];
  22202. mesh._resyncLighSource(this);
  22203. }
  22204. };
  22205. /**
  22206. * Forces the meshes to update their light related information in their rendering used effects
  22207. * @hidden Internal Use Only
  22208. */
  22209. Light.prototype._markMeshesAsLightDirty = function () {
  22210. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22211. var mesh = _a[_i];
  22212. if (mesh._lightSources.indexOf(this) !== -1) {
  22213. mesh._markSubMeshesAsLightDirty();
  22214. }
  22215. }
  22216. };
  22217. /**
  22218. * Recomputes the cached photometric scale if needed.
  22219. */
  22220. Light.prototype._computePhotometricScale = function () {
  22221. this._photometricScale = this._getPhotometricScale();
  22222. this.getScene().resetCachedMaterial();
  22223. };
  22224. /**
  22225. * Returns the Photometric Scale according to the light type and intensity mode.
  22226. */
  22227. Light.prototype._getPhotometricScale = function () {
  22228. var photometricScale = 0.0;
  22229. var lightTypeID = this.getTypeID();
  22230. //get photometric mode
  22231. var photometricMode = this.intensityMode;
  22232. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22233. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22234. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22235. }
  22236. else {
  22237. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22238. }
  22239. }
  22240. //compute photometric scale
  22241. switch (lightTypeID) {
  22242. case Light.LIGHTTYPEID_POINTLIGHT:
  22243. case Light.LIGHTTYPEID_SPOTLIGHT:
  22244. switch (photometricMode) {
  22245. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22246. photometricScale = 1.0 / (4.0 * Math.PI);
  22247. break;
  22248. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22249. photometricScale = 1.0;
  22250. break;
  22251. case Light.INTENSITYMODE_LUMINANCE:
  22252. photometricScale = this.radius * this.radius;
  22253. break;
  22254. }
  22255. break;
  22256. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22257. switch (photometricMode) {
  22258. case Light.INTENSITYMODE_ILLUMINANCE:
  22259. photometricScale = 1.0;
  22260. break;
  22261. case Light.INTENSITYMODE_LUMINANCE:
  22262. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22263. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22264. var apexAngleRadians = this.radius;
  22265. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22266. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22267. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22268. photometricScale = solidAngle;
  22269. break;
  22270. }
  22271. break;
  22272. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22273. // No fall off in hemisperic light.
  22274. photometricScale = 1.0;
  22275. break;
  22276. }
  22277. return photometricScale;
  22278. };
  22279. /**
  22280. * Reorder the light in the scene according to their defined priority.
  22281. * @hidden Internal Use Only
  22282. */
  22283. Light.prototype._reorderLightsInScene = function () {
  22284. var scene = this.getScene();
  22285. if (this._renderPriority != 0) {
  22286. scene.requireLightSorting = true;
  22287. }
  22288. this.getScene().sortLightsByPriority();
  22289. };
  22290. //lightmapMode Consts
  22291. Light._LIGHTMAP_DEFAULT = 0;
  22292. Light._LIGHTMAP_SPECULAR = 1;
  22293. Light._LIGHTMAP_SHADOWSONLY = 2;
  22294. // Intensity Mode Consts
  22295. Light._INTENSITYMODE_AUTOMATIC = 0;
  22296. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22297. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22298. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22299. Light._INTENSITYMODE_LUMINANCE = 4;
  22300. // Light types ids const.
  22301. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22302. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22303. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22304. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22305. __decorate([
  22306. BABYLON.serializeAsColor3()
  22307. ], Light.prototype, "diffuse", void 0);
  22308. __decorate([
  22309. BABYLON.serializeAsColor3()
  22310. ], Light.prototype, "specular", void 0);
  22311. __decorate([
  22312. BABYLON.serialize()
  22313. ], Light.prototype, "intensity", void 0);
  22314. __decorate([
  22315. BABYLON.serialize()
  22316. ], Light.prototype, "range", void 0);
  22317. __decorate([
  22318. BABYLON.serialize()
  22319. ], Light.prototype, "intensityMode", null);
  22320. __decorate([
  22321. BABYLON.serialize()
  22322. ], Light.prototype, "radius", null);
  22323. __decorate([
  22324. BABYLON.serialize()
  22325. ], Light.prototype, "_renderPriority", void 0);
  22326. __decorate([
  22327. BABYLON.expandToProperty("_reorderLightsInScene")
  22328. ], Light.prototype, "renderPriority", void 0);
  22329. __decorate([
  22330. BABYLON.serialize("shadowEnabled")
  22331. ], Light.prototype, "_shadowEnabled", void 0);
  22332. __decorate([
  22333. BABYLON.serialize("excludeWithLayerMask")
  22334. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22335. __decorate([
  22336. BABYLON.serialize("includeOnlyWithLayerMask")
  22337. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22338. __decorate([
  22339. BABYLON.serialize("lightmapMode")
  22340. ], Light.prototype, "_lightmapMode", void 0);
  22341. return Light;
  22342. }(BABYLON.Node));
  22343. BABYLON.Light = Light;
  22344. })(BABYLON || (BABYLON = {}));
  22345. //# sourceMappingURL=babylon.light.js.map
  22346. var BABYLON;
  22347. (function (BABYLON) {
  22348. var Camera = /** @class */ (function (_super) {
  22349. __extends(Camera, _super);
  22350. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22351. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22352. var _this = _super.call(this, name, scene) || this;
  22353. /**
  22354. * The vector the camera should consider as up.
  22355. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22356. */
  22357. _this.upVector = BABYLON.Vector3.Up();
  22358. _this.orthoLeft = null;
  22359. _this.orthoRight = null;
  22360. _this.orthoBottom = null;
  22361. _this.orthoTop = null;
  22362. /**
  22363. * FOV is set in Radians. (default is 0.8)
  22364. */
  22365. _this.fov = 0.8;
  22366. _this.minZ = 1;
  22367. _this.maxZ = 10000.0;
  22368. _this.inertia = 0.9;
  22369. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22370. _this.isIntermediate = false;
  22371. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22372. /**
  22373. * Restricts the camera to viewing objects with the same layerMask.
  22374. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22375. */
  22376. _this.layerMask = 0x0FFFFFFF;
  22377. /**
  22378. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22379. */
  22380. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22381. // Camera rig members
  22382. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22383. _this._rigCameras = new Array();
  22384. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22385. _this._skipRendering = false;
  22386. _this.customRenderTargets = new Array();
  22387. // Observables
  22388. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22389. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22390. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22391. _this.onRestoreStateObservable = new BABYLON.Observable();
  22392. // Cache
  22393. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22394. _this._projectionMatrix = new BABYLON.Matrix();
  22395. _this._doNotComputeProjectionMatrix = false;
  22396. _this._worldMatrix = BABYLON.Matrix.Identity();
  22397. _this._postProcesses = new Array();
  22398. _this._transformMatrix = BABYLON.Matrix.Zero();
  22399. _this._activeMeshes = new BABYLON.SmartArray(256);
  22400. _this._globalPosition = BABYLON.Vector3.Zero();
  22401. _this._refreshFrustumPlanes = true;
  22402. _this.getScene().addCamera(_this);
  22403. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22404. _this.getScene().activeCamera = _this;
  22405. }
  22406. _this.position = position;
  22407. return _this;
  22408. }
  22409. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22410. get: function () {
  22411. return Camera._PERSPECTIVE_CAMERA;
  22412. },
  22413. enumerable: true,
  22414. configurable: true
  22415. });
  22416. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22417. get: function () {
  22418. return Camera._ORTHOGRAPHIC_CAMERA;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22424. /**
  22425. * This is the default FOV mode for perspective cameras.
  22426. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22427. *
  22428. */
  22429. get: function () {
  22430. return Camera._FOVMODE_VERTICAL_FIXED;
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22436. /**
  22437. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22438. *
  22439. */
  22440. get: function () {
  22441. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22442. },
  22443. enumerable: true,
  22444. configurable: true
  22445. });
  22446. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22447. get: function () {
  22448. return Camera._RIG_MODE_NONE;
  22449. },
  22450. enumerable: true,
  22451. configurable: true
  22452. });
  22453. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22454. get: function () {
  22455. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22461. get: function () {
  22462. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22463. },
  22464. enumerable: true,
  22465. configurable: true
  22466. });
  22467. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22468. get: function () {
  22469. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22470. },
  22471. enumerable: true,
  22472. configurable: true
  22473. });
  22474. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22475. get: function () {
  22476. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22477. },
  22478. enumerable: true,
  22479. configurable: true
  22480. });
  22481. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22482. get: function () {
  22483. return Camera._RIG_MODE_VR;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22489. get: function () {
  22490. return Camera._RIG_MODE_WEBVR;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. /**
  22496. * Store current camera state (fov, position, etc..)
  22497. */
  22498. Camera.prototype.storeState = function () {
  22499. this._stateStored = true;
  22500. this._storedFov = this.fov;
  22501. return this;
  22502. };
  22503. /**
  22504. * Restores the camera state values if it has been stored. You must call storeState() first
  22505. */
  22506. Camera.prototype._restoreStateValues = function () {
  22507. if (!this._stateStored) {
  22508. return false;
  22509. }
  22510. this.fov = this._storedFov;
  22511. return true;
  22512. };
  22513. /**
  22514. * Restored camera state. You must call storeState() first
  22515. */
  22516. Camera.prototype.restoreState = function () {
  22517. if (this._restoreStateValues()) {
  22518. this.onRestoreStateObservable.notifyObservers(this);
  22519. return true;
  22520. }
  22521. return false;
  22522. };
  22523. Camera.prototype.getClassName = function () {
  22524. return "Camera";
  22525. };
  22526. /**
  22527. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22528. */
  22529. Camera.prototype.toString = function (fullDetails) {
  22530. var ret = "Name: " + this.name;
  22531. ret += ", type: " + this.getClassName();
  22532. if (this.animations) {
  22533. for (var i = 0; i < this.animations.length; i++) {
  22534. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22535. }
  22536. }
  22537. if (fullDetails) {
  22538. }
  22539. return ret;
  22540. };
  22541. Object.defineProperty(Camera.prototype, "globalPosition", {
  22542. get: function () {
  22543. return this._globalPosition;
  22544. },
  22545. enumerable: true,
  22546. configurable: true
  22547. });
  22548. Camera.prototype.getActiveMeshes = function () {
  22549. return this._activeMeshes;
  22550. };
  22551. Camera.prototype.isActiveMesh = function (mesh) {
  22552. return (this._activeMeshes.indexOf(mesh) !== -1);
  22553. };
  22554. /**
  22555. * Is this camera ready to be used/rendered
  22556. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22557. * @return true if the camera is ready
  22558. */
  22559. Camera.prototype.isReady = function (completeCheck) {
  22560. if (completeCheck === void 0) { completeCheck = false; }
  22561. if (completeCheck) {
  22562. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22563. var pp = _a[_i];
  22564. if (pp && !pp.isReady()) {
  22565. return false;
  22566. }
  22567. }
  22568. }
  22569. return _super.prototype.isReady.call(this, completeCheck);
  22570. };
  22571. //Cache
  22572. Camera.prototype._initCache = function () {
  22573. _super.prototype._initCache.call(this);
  22574. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22575. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22576. this._cache.mode = undefined;
  22577. this._cache.minZ = undefined;
  22578. this._cache.maxZ = undefined;
  22579. this._cache.fov = undefined;
  22580. this._cache.fovMode = undefined;
  22581. this._cache.aspectRatio = undefined;
  22582. this._cache.orthoLeft = undefined;
  22583. this._cache.orthoRight = undefined;
  22584. this._cache.orthoBottom = undefined;
  22585. this._cache.orthoTop = undefined;
  22586. this._cache.renderWidth = undefined;
  22587. this._cache.renderHeight = undefined;
  22588. };
  22589. Camera.prototype._updateCache = function (ignoreParentClass) {
  22590. if (!ignoreParentClass) {
  22591. _super.prototype._updateCache.call(this);
  22592. }
  22593. this._cache.position.copyFrom(this.position);
  22594. this._cache.upVector.copyFrom(this.upVector);
  22595. };
  22596. // Synchronized
  22597. Camera.prototype._isSynchronized = function () {
  22598. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22599. };
  22600. Camera.prototype._isSynchronizedViewMatrix = function () {
  22601. if (!_super.prototype._isSynchronized.call(this))
  22602. return false;
  22603. return this._cache.position.equals(this.position)
  22604. && this._cache.upVector.equals(this.upVector)
  22605. && this.isSynchronizedWithParent();
  22606. };
  22607. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22608. var check = this._cache.mode === this.mode
  22609. && this._cache.minZ === this.minZ
  22610. && this._cache.maxZ === this.maxZ;
  22611. if (!check) {
  22612. return false;
  22613. }
  22614. var engine = this.getEngine();
  22615. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22616. check = this._cache.fov === this.fov
  22617. && this._cache.fovMode === this.fovMode
  22618. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22619. }
  22620. else {
  22621. check = this._cache.orthoLeft === this.orthoLeft
  22622. && this._cache.orthoRight === this.orthoRight
  22623. && this._cache.orthoBottom === this.orthoBottom
  22624. && this._cache.orthoTop === this.orthoTop
  22625. && this._cache.renderWidth === engine.getRenderWidth()
  22626. && this._cache.renderHeight === engine.getRenderHeight();
  22627. }
  22628. return check;
  22629. };
  22630. // Controls
  22631. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22632. };
  22633. Camera.prototype.detachControl = function (element) {
  22634. };
  22635. Camera.prototype.update = function () {
  22636. this._checkInputs();
  22637. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22638. this._updateRigCameras();
  22639. }
  22640. };
  22641. Camera.prototype._checkInputs = function () {
  22642. this.onAfterCheckInputsObservable.notifyObservers(this);
  22643. };
  22644. Object.defineProperty(Camera.prototype, "rigCameras", {
  22645. get: function () {
  22646. return this._rigCameras;
  22647. },
  22648. enumerable: true,
  22649. configurable: true
  22650. });
  22651. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22652. get: function () {
  22653. return this._rigPostProcess;
  22654. },
  22655. enumerable: true,
  22656. configurable: true
  22657. });
  22658. /**
  22659. * Internal, gets the first post proces.
  22660. * @returns the first post process to be run on this camera.
  22661. */
  22662. Camera.prototype._getFirstPostProcess = function () {
  22663. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22664. if (this._postProcesses[ppIndex] !== null) {
  22665. return this._postProcesses[ppIndex];
  22666. }
  22667. }
  22668. return null;
  22669. };
  22670. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22671. // invalidate framebuffer
  22672. var firstPostProcess = this._getFirstPostProcess();
  22673. if (firstPostProcess) {
  22674. firstPostProcess.markTextureDirty();
  22675. }
  22676. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22677. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22678. var cam = this._rigCameras[i];
  22679. var rigPostProcess = cam._rigPostProcess;
  22680. // for VR rig, there does not have to be a post process
  22681. if (rigPostProcess) {
  22682. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22683. if (isPass) {
  22684. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22685. cam.isIntermediate = this._postProcesses.length === 0;
  22686. }
  22687. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22688. rigPostProcess.markTextureDirty();
  22689. }
  22690. else {
  22691. cam._postProcesses = this._postProcesses.slice(0);
  22692. }
  22693. }
  22694. };
  22695. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22696. if (insertAt === void 0) { insertAt = null; }
  22697. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22698. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22699. return 0;
  22700. }
  22701. if (insertAt == null || insertAt < 0) {
  22702. this._postProcesses.push(postProcess);
  22703. }
  22704. else if (this._postProcesses[insertAt] === null) {
  22705. this._postProcesses[insertAt] = postProcess;
  22706. }
  22707. else {
  22708. this._postProcesses.splice(insertAt, 0, postProcess);
  22709. }
  22710. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22711. return this._postProcesses.indexOf(postProcess);
  22712. };
  22713. Camera.prototype.detachPostProcess = function (postProcess) {
  22714. var idx = this._postProcesses.indexOf(postProcess);
  22715. if (idx !== -1) {
  22716. this._postProcesses[idx] = null;
  22717. }
  22718. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22719. };
  22720. Camera.prototype.getWorldMatrix = function () {
  22721. if (this._isSynchronizedViewMatrix()) {
  22722. return this._worldMatrix;
  22723. }
  22724. // Getting the the view matrix will also compute the world matrix.
  22725. this.getViewMatrix();
  22726. return this._worldMatrix;
  22727. };
  22728. Camera.prototype._getViewMatrix = function () {
  22729. return BABYLON.Matrix.Identity();
  22730. };
  22731. Camera.prototype.getViewMatrix = function (force) {
  22732. if (!force && this._isSynchronizedViewMatrix()) {
  22733. return this._computedViewMatrix;
  22734. }
  22735. this.updateCache();
  22736. this._computedViewMatrix = this._getViewMatrix();
  22737. this._currentRenderId = this.getScene().getRenderId();
  22738. this._childRenderId = this._currentRenderId;
  22739. this._refreshFrustumPlanes = true;
  22740. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22741. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22742. }
  22743. this.onViewMatrixChangedObservable.notifyObservers(this);
  22744. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22745. return this._computedViewMatrix;
  22746. };
  22747. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22748. this._doNotComputeProjectionMatrix = true;
  22749. if (projection !== undefined) {
  22750. this._projectionMatrix = projection;
  22751. }
  22752. };
  22753. ;
  22754. Camera.prototype.unfreezeProjectionMatrix = function () {
  22755. this._doNotComputeProjectionMatrix = false;
  22756. };
  22757. ;
  22758. Camera.prototype.getProjectionMatrix = function (force) {
  22759. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22760. return this._projectionMatrix;
  22761. }
  22762. // Cache
  22763. this._cache.mode = this.mode;
  22764. this._cache.minZ = this.minZ;
  22765. this._cache.maxZ = this.maxZ;
  22766. // Matrix
  22767. this._refreshFrustumPlanes = true;
  22768. var engine = this.getEngine();
  22769. var scene = this.getScene();
  22770. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22771. this._cache.fov = this.fov;
  22772. this._cache.fovMode = this.fovMode;
  22773. this._cache.aspectRatio = engine.getAspectRatio(this);
  22774. if (this.minZ <= 0) {
  22775. this.minZ = 0.1;
  22776. }
  22777. if (scene.useRightHandedSystem) {
  22778. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22779. }
  22780. else {
  22781. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22782. }
  22783. }
  22784. else {
  22785. var halfWidth = engine.getRenderWidth() / 2.0;
  22786. var halfHeight = engine.getRenderHeight() / 2.0;
  22787. if (scene.useRightHandedSystem) {
  22788. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22789. }
  22790. else {
  22791. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22792. }
  22793. this._cache.orthoLeft = this.orthoLeft;
  22794. this._cache.orthoRight = this.orthoRight;
  22795. this._cache.orthoBottom = this.orthoBottom;
  22796. this._cache.orthoTop = this.orthoTop;
  22797. this._cache.renderWidth = engine.getRenderWidth();
  22798. this._cache.renderHeight = engine.getRenderHeight();
  22799. }
  22800. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22801. return this._projectionMatrix;
  22802. };
  22803. Camera.prototype.getTranformationMatrix = function () {
  22804. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22805. return this._transformMatrix;
  22806. };
  22807. Camera.prototype.updateFrustumPlanes = function () {
  22808. if (!this._refreshFrustumPlanes) {
  22809. return;
  22810. }
  22811. this.getTranformationMatrix();
  22812. if (!this._frustumPlanes) {
  22813. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22814. }
  22815. else {
  22816. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22817. }
  22818. this._refreshFrustumPlanes = false;
  22819. };
  22820. Camera.prototype.isInFrustum = function (target) {
  22821. this.updateFrustumPlanes();
  22822. return target.isInFrustum(this._frustumPlanes);
  22823. };
  22824. Camera.prototype.isCompletelyInFrustum = function (target) {
  22825. this.updateFrustumPlanes();
  22826. return target.isCompletelyInFrustum(this._frustumPlanes);
  22827. };
  22828. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22829. if (length === void 0) { length = 100; }
  22830. if (!transform) {
  22831. transform = this.getWorldMatrix();
  22832. }
  22833. if (!origin) {
  22834. origin = this.position;
  22835. }
  22836. var forward = new BABYLON.Vector3(0, 0, 1);
  22837. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22838. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22839. return new BABYLON.Ray(origin, direction, length);
  22840. };
  22841. /**
  22842. * Releases resources associated with this node.
  22843. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22844. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22845. */
  22846. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22847. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22848. // Observables
  22849. this.onViewMatrixChangedObservable.clear();
  22850. this.onProjectionMatrixChangedObservable.clear();
  22851. this.onAfterCheckInputsObservable.clear();
  22852. this.onRestoreStateObservable.clear();
  22853. // Inputs
  22854. if (this.inputs) {
  22855. this.inputs.clear();
  22856. }
  22857. // Animations
  22858. this.getScene().stopAnimation(this);
  22859. // Remove from scene
  22860. this.getScene().removeCamera(this);
  22861. while (this._rigCameras.length > 0) {
  22862. var camera = this._rigCameras.pop();
  22863. if (camera) {
  22864. camera.dispose();
  22865. }
  22866. }
  22867. // Postprocesses
  22868. if (this._rigPostProcess) {
  22869. this._rigPostProcess.dispose(this);
  22870. this._rigPostProcess = null;
  22871. this._postProcesses = [];
  22872. }
  22873. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22874. this._rigPostProcess = null;
  22875. this._postProcesses = [];
  22876. }
  22877. else {
  22878. var i = this._postProcesses.length;
  22879. while (--i >= 0) {
  22880. var postProcess = this._postProcesses[i];
  22881. if (postProcess) {
  22882. postProcess.dispose(this);
  22883. }
  22884. }
  22885. }
  22886. // Render targets
  22887. var i = this.customRenderTargets.length;
  22888. while (--i >= 0) {
  22889. this.customRenderTargets[i].dispose();
  22890. }
  22891. this.customRenderTargets = [];
  22892. // Active Meshes
  22893. this._activeMeshes.dispose();
  22894. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22895. };
  22896. Object.defineProperty(Camera.prototype, "leftCamera", {
  22897. // ---- Camera rigs section ----
  22898. get: function () {
  22899. if (this._rigCameras.length < 1) {
  22900. return null;
  22901. }
  22902. return this._rigCameras[0];
  22903. },
  22904. enumerable: true,
  22905. configurable: true
  22906. });
  22907. Object.defineProperty(Camera.prototype, "rightCamera", {
  22908. get: function () {
  22909. if (this._rigCameras.length < 2) {
  22910. return null;
  22911. }
  22912. return this._rigCameras[1];
  22913. },
  22914. enumerable: true,
  22915. configurable: true
  22916. });
  22917. Camera.prototype.getLeftTarget = function () {
  22918. if (this._rigCameras.length < 1) {
  22919. return null;
  22920. }
  22921. return this._rigCameras[0].getTarget();
  22922. };
  22923. Camera.prototype.getRightTarget = function () {
  22924. if (this._rigCameras.length < 2) {
  22925. return null;
  22926. }
  22927. return this._rigCameras[1].getTarget();
  22928. };
  22929. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22930. if (this.cameraRigMode === mode) {
  22931. return;
  22932. }
  22933. while (this._rigCameras.length > 0) {
  22934. var camera = this._rigCameras.pop();
  22935. if (camera) {
  22936. camera.dispose();
  22937. }
  22938. }
  22939. this.cameraRigMode = mode;
  22940. this._cameraRigParams = {};
  22941. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22942. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22943. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22944. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22945. // create the rig cameras, unless none
  22946. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22947. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22948. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22949. if (leftCamera && rightCamera) {
  22950. this._rigCameras.push(leftCamera);
  22951. this._rigCameras.push(rightCamera);
  22952. }
  22953. }
  22954. switch (this.cameraRigMode) {
  22955. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22956. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22957. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22958. break;
  22959. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22960. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22961. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22962. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22963. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22964. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22965. break;
  22966. case Camera.RIG_MODE_VR:
  22967. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22968. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22969. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22970. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22971. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22972. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22973. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22974. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22975. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22976. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22977. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22978. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22979. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22980. if (metrics.compensateDistortion) {
  22981. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22982. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22983. }
  22984. break;
  22985. case Camera.RIG_MODE_WEBVR:
  22986. if (rigParams.vrDisplay) {
  22987. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22988. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22989. //Left eye
  22990. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22991. this._rigCameras[0].setCameraRigParameter("left", true);
  22992. //leaving this for future reference
  22993. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22994. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22995. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22996. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22997. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22998. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22999. this._rigCameras[0].parent = this;
  23000. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23001. //Right eye
  23002. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23003. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23004. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23005. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23006. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23007. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23008. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23009. this._rigCameras[1].parent = this;
  23010. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23011. if (Camera.UseAlternateWebVRRendering) {
  23012. this._rigCameras[1]._skipRendering = true;
  23013. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23014. }
  23015. }
  23016. break;
  23017. }
  23018. this._cascadePostProcessesToRigCams();
  23019. this.update();
  23020. };
  23021. Camera.prototype._getVRProjectionMatrix = function () {
  23022. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23023. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23024. return this._projectionMatrix;
  23025. };
  23026. Camera.prototype._updateCameraRotationMatrix = function () {
  23027. //Here for WebVR
  23028. };
  23029. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23030. //Here for WebVR
  23031. };
  23032. /**
  23033. * This function MUST be overwritten by the different WebVR cameras available.
  23034. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23035. */
  23036. Camera.prototype._getWebVRProjectionMatrix = function () {
  23037. return BABYLON.Matrix.Identity();
  23038. };
  23039. /**
  23040. * This function MUST be overwritten by the different WebVR cameras available.
  23041. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23042. */
  23043. Camera.prototype._getWebVRViewMatrix = function () {
  23044. return BABYLON.Matrix.Identity();
  23045. };
  23046. Camera.prototype.setCameraRigParameter = function (name, value) {
  23047. if (!this._cameraRigParams) {
  23048. this._cameraRigParams = {};
  23049. }
  23050. this._cameraRigParams[name] = value;
  23051. //provisionnally:
  23052. if (name === "interaxialDistance") {
  23053. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23054. }
  23055. };
  23056. /**
  23057. * needs to be overridden by children so sub has required properties to be copied
  23058. */
  23059. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23060. return null;
  23061. };
  23062. /**
  23063. * May need to be overridden by children
  23064. */
  23065. Camera.prototype._updateRigCameras = function () {
  23066. for (var i = 0; i < this._rigCameras.length; i++) {
  23067. this._rigCameras[i].minZ = this.minZ;
  23068. this._rigCameras[i].maxZ = this.maxZ;
  23069. this._rigCameras[i].fov = this.fov;
  23070. }
  23071. // only update viewport when ANAGLYPH
  23072. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23073. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23074. }
  23075. };
  23076. Camera.prototype._setupInputs = function () {
  23077. };
  23078. Camera.prototype.serialize = function () {
  23079. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23080. // Type
  23081. serializationObject.type = this.getClassName();
  23082. // Parent
  23083. if (this.parent) {
  23084. serializationObject.parentId = this.parent.id;
  23085. }
  23086. if (this.inputs) {
  23087. this.inputs.serialize(serializationObject);
  23088. }
  23089. // Animations
  23090. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23091. serializationObject.ranges = this.serializeAnimationRanges();
  23092. return serializationObject;
  23093. };
  23094. Camera.prototype.clone = function (name) {
  23095. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23096. };
  23097. Camera.prototype.getDirection = function (localAxis) {
  23098. var result = BABYLON.Vector3.Zero();
  23099. this.getDirectionToRef(localAxis, result);
  23100. return result;
  23101. };
  23102. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23103. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23104. };
  23105. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23106. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23107. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23108. switch (type) {
  23109. case "ArcRotateCamera":
  23110. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23111. case "DeviceOrientationCamera":
  23112. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23113. case "FollowCamera":
  23114. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23115. case "ArcFollowCamera":
  23116. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23117. case "GamepadCamera":
  23118. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23119. case "TouchCamera":
  23120. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23121. case "VirtualJoysticksCamera":
  23122. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23123. case "WebVRFreeCamera":
  23124. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23125. case "WebVRGamepadCamera":
  23126. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23127. case "VRDeviceOrientationFreeCamera":
  23128. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23129. case "VRDeviceOrientationGamepadCamera":
  23130. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23131. case "AnaglyphArcRotateCamera":
  23132. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23133. case "AnaglyphFreeCamera":
  23134. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23135. case "AnaglyphGamepadCamera":
  23136. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23137. case "AnaglyphUniversalCamera":
  23138. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23139. case "StereoscopicArcRotateCamera":
  23140. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23141. case "StereoscopicFreeCamera":
  23142. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23143. case "StereoscopicGamepadCamera":
  23144. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23145. case "StereoscopicUniversalCamera":
  23146. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23147. case "FreeCamera": // Forcing Universal here
  23148. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23149. default: // Universal Camera is the default value
  23150. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23151. }
  23152. };
  23153. Camera.prototype.computeWorldMatrix = function () {
  23154. return this.getWorldMatrix();
  23155. };
  23156. Camera.Parse = function (parsedCamera, scene) {
  23157. var type = parsedCamera.type;
  23158. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23159. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23160. // Parent
  23161. if (parsedCamera.parentId) {
  23162. camera._waitingParentId = parsedCamera.parentId;
  23163. }
  23164. //If camera has an input manager, let it parse inputs settings
  23165. if (camera.inputs) {
  23166. camera.inputs.parse(parsedCamera);
  23167. camera._setupInputs();
  23168. }
  23169. if (camera.setPosition) { // need to force position
  23170. camera.position.copyFromFloats(0, 0, 0);
  23171. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23172. }
  23173. // Target
  23174. if (parsedCamera.target) {
  23175. if (camera.setTarget) {
  23176. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23177. }
  23178. }
  23179. // Apply 3d rig, when found
  23180. if (parsedCamera.cameraRigMode) {
  23181. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23182. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23183. }
  23184. // Animations
  23185. if (parsedCamera.animations) {
  23186. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23187. var parsedAnimation = parsedCamera.animations[animationIndex];
  23188. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23189. }
  23190. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23191. }
  23192. if (parsedCamera.autoAnimate) {
  23193. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23194. }
  23195. return camera;
  23196. };
  23197. // Statics
  23198. Camera._PERSPECTIVE_CAMERA = 0;
  23199. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23200. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23201. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23202. Camera._RIG_MODE_NONE = 0;
  23203. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23204. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23205. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23206. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23207. Camera._RIG_MODE_VR = 20;
  23208. Camera._RIG_MODE_WEBVR = 21;
  23209. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23210. Camera.UseAlternateWebVRRendering = false;
  23211. __decorate([
  23212. BABYLON.serializeAsVector3()
  23213. ], Camera.prototype, "position", void 0);
  23214. __decorate([
  23215. BABYLON.serializeAsVector3()
  23216. ], Camera.prototype, "upVector", void 0);
  23217. __decorate([
  23218. BABYLON.serialize()
  23219. ], Camera.prototype, "orthoLeft", void 0);
  23220. __decorate([
  23221. BABYLON.serialize()
  23222. ], Camera.prototype, "orthoRight", void 0);
  23223. __decorate([
  23224. BABYLON.serialize()
  23225. ], Camera.prototype, "orthoBottom", void 0);
  23226. __decorate([
  23227. BABYLON.serialize()
  23228. ], Camera.prototype, "orthoTop", void 0);
  23229. __decorate([
  23230. BABYLON.serialize()
  23231. ], Camera.prototype, "fov", void 0);
  23232. __decorate([
  23233. BABYLON.serialize()
  23234. ], Camera.prototype, "minZ", void 0);
  23235. __decorate([
  23236. BABYLON.serialize()
  23237. ], Camera.prototype, "maxZ", void 0);
  23238. __decorate([
  23239. BABYLON.serialize()
  23240. ], Camera.prototype, "inertia", void 0);
  23241. __decorate([
  23242. BABYLON.serialize()
  23243. ], Camera.prototype, "mode", void 0);
  23244. __decorate([
  23245. BABYLON.serialize()
  23246. ], Camera.prototype, "layerMask", void 0);
  23247. __decorate([
  23248. BABYLON.serialize()
  23249. ], Camera.prototype, "fovMode", void 0);
  23250. __decorate([
  23251. BABYLON.serialize()
  23252. ], Camera.prototype, "cameraRigMode", void 0);
  23253. __decorate([
  23254. BABYLON.serialize()
  23255. ], Camera.prototype, "interaxialDistance", void 0);
  23256. __decorate([
  23257. BABYLON.serialize()
  23258. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23259. return Camera;
  23260. }(BABYLON.Node));
  23261. BABYLON.Camera = Camera;
  23262. })(BABYLON || (BABYLON = {}));
  23263. //# sourceMappingURL=babylon.camera.js.map
  23264. var BABYLON;
  23265. (function (BABYLON) {
  23266. var RenderingManager = /** @class */ (function () {
  23267. function RenderingManager(scene) {
  23268. this._renderingGroups = new Array();
  23269. this._autoClearDepthStencil = {};
  23270. this._customOpaqueSortCompareFn = {};
  23271. this._customAlphaTestSortCompareFn = {};
  23272. this._customTransparentSortCompareFn = {};
  23273. this._renderinGroupInfo = null;
  23274. this._scene = scene;
  23275. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23276. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23277. }
  23278. }
  23279. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23280. if (depth === void 0) { depth = true; }
  23281. if (stencil === void 0) { stencil = true; }
  23282. if (this._depthStencilBufferAlreadyCleaned) {
  23283. return;
  23284. }
  23285. this._scene.getEngine().clear(null, false, depth, stencil);
  23286. this._depthStencilBufferAlreadyCleaned = true;
  23287. };
  23288. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23289. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23290. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23291. var info = null;
  23292. if (observable) {
  23293. if (!this._renderinGroupInfo) {
  23294. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23295. }
  23296. info = this._renderinGroupInfo;
  23297. info.scene = this._scene;
  23298. info.camera = this._scene.activeCamera;
  23299. }
  23300. // Dispatch sprites
  23301. if (renderSprites) {
  23302. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23303. var manager = this._scene.spriteManagers[index];
  23304. this.dispatchSprites(manager);
  23305. }
  23306. }
  23307. // Render
  23308. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23309. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23310. var renderingGroup = this._renderingGroups[index];
  23311. if (!renderingGroup && !observable)
  23312. continue;
  23313. var renderingGroupMask = 0;
  23314. // Fire PRECLEAR stage
  23315. if (observable && info) {
  23316. renderingGroupMask = Math.pow(2, index);
  23317. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23318. info.renderingGroupId = index;
  23319. observable.notifyObservers(info, renderingGroupMask);
  23320. }
  23321. // Clear depth/stencil if needed
  23322. if (RenderingManager.AUTOCLEAR) {
  23323. var autoClear = this._autoClearDepthStencil[index];
  23324. if (autoClear && autoClear.autoClear) {
  23325. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23326. }
  23327. }
  23328. if (observable && info) {
  23329. // Fire PREOPAQUE stage
  23330. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23331. observable.notifyObservers(info, renderingGroupMask);
  23332. // Fire PRETRANSPARENT stage
  23333. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23334. observable.notifyObservers(info, renderingGroupMask);
  23335. }
  23336. if (renderingGroup) {
  23337. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23338. var step = _a[_i];
  23339. step.action(index);
  23340. }
  23341. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23342. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23343. var step = _c[_b];
  23344. step.action(index);
  23345. }
  23346. }
  23347. // Fire POSTTRANSPARENT stage
  23348. if (observable && info) {
  23349. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23350. observable.notifyObservers(info, renderingGroupMask);
  23351. }
  23352. }
  23353. };
  23354. RenderingManager.prototype.reset = function () {
  23355. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23356. var renderingGroup = this._renderingGroups[index];
  23357. if (renderingGroup) {
  23358. renderingGroup.prepare();
  23359. }
  23360. }
  23361. };
  23362. RenderingManager.prototype.dispose = function () {
  23363. this.freeRenderingGroups();
  23364. this._renderingGroups.length = 0;
  23365. };
  23366. /**
  23367. * Clear the info related to rendering groups preventing retention points during dispose.
  23368. */
  23369. RenderingManager.prototype.freeRenderingGroups = function () {
  23370. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23371. var renderingGroup = this._renderingGroups[index];
  23372. if (renderingGroup) {
  23373. renderingGroup.dispose();
  23374. }
  23375. }
  23376. };
  23377. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23378. if (this._renderingGroups[renderingGroupId] === undefined) {
  23379. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23380. }
  23381. };
  23382. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23383. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23384. this._prepareRenderingGroup(renderingGroupId);
  23385. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23386. };
  23387. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23388. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23389. this._prepareRenderingGroup(renderingGroupId);
  23390. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23391. };
  23392. /**
  23393. * @param subMesh The submesh to dispatch
  23394. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23395. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23396. */
  23397. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23398. if (mesh === undefined) {
  23399. mesh = subMesh.getMesh();
  23400. }
  23401. var renderingGroupId = mesh.renderingGroupId || 0;
  23402. this._prepareRenderingGroup(renderingGroupId);
  23403. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23404. };
  23405. /**
  23406. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23407. * This allowed control for front to back rendering or reversly depending of the special needs.
  23408. *
  23409. * @param renderingGroupId The rendering group id corresponding to its index
  23410. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23411. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23412. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23413. */
  23414. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23415. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23416. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23417. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23418. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23419. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23420. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23421. if (this._renderingGroups[renderingGroupId]) {
  23422. var group = this._renderingGroups[renderingGroupId];
  23423. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23424. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23425. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23426. }
  23427. };
  23428. /**
  23429. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23430. *
  23431. * @param renderingGroupId The rendering group id corresponding to its index
  23432. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23433. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23434. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23435. */
  23436. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23437. if (depth === void 0) { depth = true; }
  23438. if (stencil === void 0) { stencil = true; }
  23439. this._autoClearDepthStencil[renderingGroupId] = {
  23440. autoClear: autoClearDepthStencil,
  23441. depth: depth,
  23442. stencil: stencil
  23443. };
  23444. };
  23445. /**
  23446. * The max id used for rendering groups (not included)
  23447. */
  23448. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23449. /**
  23450. * The min id used for rendering groups (included)
  23451. */
  23452. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23453. /**
  23454. * Used to globally prevent autoclearing scenes.
  23455. */
  23456. RenderingManager.AUTOCLEAR = true;
  23457. return RenderingManager;
  23458. }());
  23459. BABYLON.RenderingManager = RenderingManager;
  23460. })(BABYLON || (BABYLON = {}));
  23461. //# sourceMappingURL=babylon.renderingManager.js.map
  23462. var BABYLON;
  23463. (function (BABYLON) {
  23464. var RenderingGroup = /** @class */ (function () {
  23465. /**
  23466. * Creates a new rendering group.
  23467. * @param index The rendering group index
  23468. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23469. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23470. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23471. */
  23472. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23473. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23474. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23475. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23476. this.index = index;
  23477. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23478. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23479. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23480. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23481. this._particleSystems = new BABYLON.SmartArray(256);
  23482. this._spriteManagers = new BABYLON.SmartArray(256);
  23483. this._edgesRenderers = new BABYLON.SmartArray(16);
  23484. this._scene = scene;
  23485. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23486. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23487. this.transparentSortCompareFn = transparentSortCompareFn;
  23488. }
  23489. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23490. /**
  23491. * Set the opaque sort comparison function.
  23492. * If null the sub meshes will be render in the order they were created
  23493. */
  23494. set: function (value) {
  23495. this._opaqueSortCompareFn = value;
  23496. if (value) {
  23497. this._renderOpaque = this.renderOpaqueSorted;
  23498. }
  23499. else {
  23500. this._renderOpaque = RenderingGroup.renderUnsorted;
  23501. }
  23502. },
  23503. enumerable: true,
  23504. configurable: true
  23505. });
  23506. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23507. /**
  23508. * Set the alpha test sort comparison function.
  23509. * If null the sub meshes will be render in the order they were created
  23510. */
  23511. set: function (value) {
  23512. this._alphaTestSortCompareFn = value;
  23513. if (value) {
  23514. this._renderAlphaTest = this.renderAlphaTestSorted;
  23515. }
  23516. else {
  23517. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23518. }
  23519. },
  23520. enumerable: true,
  23521. configurable: true
  23522. });
  23523. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23524. /**
  23525. * Set the transparent sort comparison function.
  23526. * If null the sub meshes will be render in the order they were created
  23527. */
  23528. set: function (value) {
  23529. if (value) {
  23530. this._transparentSortCompareFn = value;
  23531. }
  23532. else {
  23533. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23534. }
  23535. this._renderTransparent = this.renderTransparentSorted;
  23536. },
  23537. enumerable: true,
  23538. configurable: true
  23539. });
  23540. /**
  23541. * Render all the sub meshes contained in the group.
  23542. * @param customRenderFunction Used to override the default render behaviour of the group.
  23543. * @returns true if rendered some submeshes.
  23544. */
  23545. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23546. if (customRenderFunction) {
  23547. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23548. return;
  23549. }
  23550. var engine = this._scene.getEngine();
  23551. // Depth only
  23552. if (this._depthOnlySubMeshes.length !== 0) {
  23553. engine.setColorWrite(false);
  23554. this._renderAlphaTest(this._depthOnlySubMeshes);
  23555. engine.setColorWrite(true);
  23556. }
  23557. // Opaque
  23558. if (this._opaqueSubMeshes.length !== 0) {
  23559. this._renderOpaque(this._opaqueSubMeshes);
  23560. }
  23561. // Alpha test
  23562. if (this._alphaTestSubMeshes.length !== 0) {
  23563. this._renderAlphaTest(this._alphaTestSubMeshes);
  23564. }
  23565. var stencilState = engine.getStencilBuffer();
  23566. engine.setStencilBuffer(false);
  23567. // Sprites
  23568. if (renderSprites) {
  23569. this._renderSprites();
  23570. }
  23571. // Particles
  23572. if (renderParticles) {
  23573. this._renderParticles(activeMeshes);
  23574. }
  23575. if (this.onBeforeTransparentRendering) {
  23576. this.onBeforeTransparentRendering();
  23577. }
  23578. // Transparent
  23579. if (this._transparentSubMeshes.length !== 0) {
  23580. this._renderTransparent(this._transparentSubMeshes);
  23581. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23582. }
  23583. // Set back stencil to false in case it changes before the edge renderer.
  23584. engine.setStencilBuffer(false);
  23585. // Edges
  23586. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23587. this._edgesRenderers.data[edgesRendererIndex].render();
  23588. }
  23589. // Restore Stencil state.
  23590. engine.setStencilBuffer(stencilState);
  23591. };
  23592. /**
  23593. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23594. * @param subMeshes The submeshes to render
  23595. */
  23596. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23597. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23598. };
  23599. /**
  23600. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23601. * @param subMeshes The submeshes to render
  23602. */
  23603. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23604. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23605. };
  23606. /**
  23607. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23608. * @param subMeshes The submeshes to render
  23609. */
  23610. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23611. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23612. };
  23613. /**
  23614. * Renders the submeshes in a specified order.
  23615. * @param subMeshes The submeshes to sort before render
  23616. * @param sortCompareFn The comparison function use to sort
  23617. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23618. * @param transparent Specifies to activate blending if true
  23619. */
  23620. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23621. var subIndex = 0;
  23622. var subMesh;
  23623. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23624. for (; subIndex < subMeshes.length; subIndex++) {
  23625. subMesh = subMeshes.data[subIndex];
  23626. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23627. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23628. }
  23629. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23630. if (sortCompareFn) {
  23631. sortedArray.sort(sortCompareFn);
  23632. }
  23633. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23634. subMesh = sortedArray[subIndex];
  23635. if (transparent) {
  23636. var material = subMesh.getMaterial();
  23637. if (material && material.needDepthPrePass) {
  23638. var engine = material.getScene().getEngine();
  23639. engine.setColorWrite(false);
  23640. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23641. subMesh.render(false);
  23642. engine.setColorWrite(true);
  23643. }
  23644. }
  23645. subMesh.render(transparent);
  23646. }
  23647. };
  23648. /**
  23649. * Renders the submeshes in the order they were dispatched (no sort applied).
  23650. * @param subMeshes The submeshes to render
  23651. */
  23652. RenderingGroup.renderUnsorted = function (subMeshes) {
  23653. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23654. var submesh = subMeshes.data[subIndex];
  23655. submesh.render(false);
  23656. }
  23657. };
  23658. /**
  23659. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23660. * are rendered back to front if in the same alpha index.
  23661. *
  23662. * @param a The first submesh
  23663. * @param b The second submesh
  23664. * @returns The result of the comparison
  23665. */
  23666. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23667. // Alpha index first
  23668. if (a._alphaIndex > b._alphaIndex) {
  23669. return 1;
  23670. }
  23671. if (a._alphaIndex < b._alphaIndex) {
  23672. return -1;
  23673. }
  23674. // Then distance to camera
  23675. return RenderingGroup.backToFrontSortCompare(a, b);
  23676. };
  23677. /**
  23678. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23679. * are rendered back to front.
  23680. *
  23681. * @param a The first submesh
  23682. * @param b The second submesh
  23683. * @returns The result of the comparison
  23684. */
  23685. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23686. // Then distance to camera
  23687. if (a._distanceToCamera < b._distanceToCamera) {
  23688. return 1;
  23689. }
  23690. if (a._distanceToCamera > b._distanceToCamera) {
  23691. return -1;
  23692. }
  23693. return 0;
  23694. };
  23695. /**
  23696. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23697. * are rendered front to back (prevent overdraw).
  23698. *
  23699. * @param a The first submesh
  23700. * @param b The second submesh
  23701. * @returns The result of the comparison
  23702. */
  23703. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23704. // Then distance to camera
  23705. if (a._distanceToCamera < b._distanceToCamera) {
  23706. return -1;
  23707. }
  23708. if (a._distanceToCamera > b._distanceToCamera) {
  23709. return 1;
  23710. }
  23711. return 0;
  23712. };
  23713. /**
  23714. * Resets the different lists of submeshes to prepare a new frame.
  23715. */
  23716. RenderingGroup.prototype.prepare = function () {
  23717. this._opaqueSubMeshes.reset();
  23718. this._transparentSubMeshes.reset();
  23719. this._alphaTestSubMeshes.reset();
  23720. this._depthOnlySubMeshes.reset();
  23721. this._particleSystems.reset();
  23722. this._spriteManagers.reset();
  23723. this._edgesRenderers.reset();
  23724. };
  23725. RenderingGroup.prototype.dispose = function () {
  23726. this._opaqueSubMeshes.dispose();
  23727. this._transparentSubMeshes.dispose();
  23728. this._alphaTestSubMeshes.dispose();
  23729. this._depthOnlySubMeshes.dispose();
  23730. this._particleSystems.dispose();
  23731. this._spriteManagers.dispose();
  23732. this._edgesRenderers.dispose();
  23733. };
  23734. /**
  23735. * Inserts the submesh in its correct queue depending on its material.
  23736. * @param subMesh The submesh to dispatch
  23737. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23738. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23739. */
  23740. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23741. // Get mesh and materials if not provided
  23742. if (mesh === undefined) {
  23743. mesh = subMesh.getMesh();
  23744. }
  23745. if (material === undefined) {
  23746. material = subMesh.getMaterial();
  23747. }
  23748. if (material === null || material === undefined) {
  23749. return;
  23750. }
  23751. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23752. this._transparentSubMeshes.push(subMesh);
  23753. }
  23754. else if (material.needAlphaTesting()) { // Alpha test
  23755. if (material.needDepthPrePass) {
  23756. this._depthOnlySubMeshes.push(subMesh);
  23757. }
  23758. this._alphaTestSubMeshes.push(subMesh);
  23759. }
  23760. else {
  23761. if (material.needDepthPrePass) {
  23762. this._depthOnlySubMeshes.push(subMesh);
  23763. }
  23764. this._opaqueSubMeshes.push(subMesh); // Opaque
  23765. }
  23766. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23767. this._edgesRenderers.push(mesh._edgesRenderer);
  23768. }
  23769. };
  23770. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23771. this._spriteManagers.push(spriteManager);
  23772. };
  23773. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23774. this._particleSystems.push(particleSystem);
  23775. };
  23776. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23777. if (this._particleSystems.length === 0) {
  23778. return;
  23779. }
  23780. // Particles
  23781. var activeCamera = this._scene.activeCamera;
  23782. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23783. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23784. var particleSystem = this._particleSystems.data[particleIndex];
  23785. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23786. continue;
  23787. }
  23788. var emitter = particleSystem.emitter;
  23789. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23790. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23791. }
  23792. }
  23793. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23794. };
  23795. RenderingGroup.prototype._renderSprites = function () {
  23796. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23797. return;
  23798. }
  23799. // Sprites
  23800. var activeCamera = this._scene.activeCamera;
  23801. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23802. for (var id = 0; id < this._spriteManagers.length; id++) {
  23803. var spriteManager = this._spriteManagers.data[id];
  23804. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23805. spriteManager.render();
  23806. }
  23807. }
  23808. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23809. };
  23810. return RenderingGroup;
  23811. }());
  23812. BABYLON.RenderingGroup = RenderingGroup;
  23813. })(BABYLON || (BABYLON = {}));
  23814. //# sourceMappingURL=babylon.renderingGroup.js.map
  23815. var BABYLON;
  23816. (function (BABYLON) {
  23817. /**
  23818. * Groups all the scene component constants in one place to ease maintenance.
  23819. * @hidden
  23820. */
  23821. var SceneComponentConstants = /** @class */ (function () {
  23822. function SceneComponentConstants() {
  23823. }
  23824. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23825. SceneComponentConstants.NAME_LAYER = "Layer";
  23826. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23827. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23828. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23829. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23830. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23831. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23832. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23833. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23834. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23835. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23836. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23837. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23838. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23839. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23840. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23841. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23842. return SceneComponentConstants;
  23843. }());
  23844. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23845. /**
  23846. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23847. * @hidden
  23848. */
  23849. var Stage = /** @class */ (function (_super) {
  23850. __extends(Stage, _super);
  23851. /**
  23852. * Hide ctor from the rest of the world.
  23853. * @param items The items to add.
  23854. */
  23855. function Stage(items) {
  23856. return _super.apply(this, items) || this;
  23857. }
  23858. /**
  23859. * Creates a new Stage.
  23860. * @returns A new instance of a Stage
  23861. */
  23862. Stage.Create = function () {
  23863. return Object.create(Stage.prototype);
  23864. };
  23865. /**
  23866. * Registers a step in an ordered way in the targeted stage.
  23867. * @param index Defines the position to register the step in
  23868. * @param component Defines the component attached to the step
  23869. * @param action Defines the action to launch during the step
  23870. */
  23871. Stage.prototype.registerStep = function (index, component, action) {
  23872. var i = 0;
  23873. var maxIndex = Number.MAX_VALUE;
  23874. for (; i < this.length && i < maxIndex; i++) {
  23875. var step = this[i];
  23876. maxIndex = step.index;
  23877. }
  23878. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23879. };
  23880. /**
  23881. * Clears all the steps from the stage.
  23882. */
  23883. Stage.prototype.clear = function () {
  23884. this.length = 0;
  23885. };
  23886. return Stage;
  23887. }(Array));
  23888. BABYLON.Stage = Stage;
  23889. })(BABYLON || (BABYLON = {}));
  23890. //# sourceMappingURL=babylon.sceneComponent.js.map
  23891. var BABYLON;
  23892. (function (BABYLON) {
  23893. /**
  23894. * Base class of the scene acting as a container for the different elements composing a scene.
  23895. * This class is dynamically extended by the different components of the scene increasing
  23896. * flexibility and reducing coupling.
  23897. */
  23898. var AbstractScene = /** @class */ (function () {
  23899. function AbstractScene() {
  23900. /** All of the cameras added to this scene
  23901. * @see http://doc.babylonjs.com/babylon101/cameras
  23902. */
  23903. this.cameras = new Array();
  23904. /**
  23905. * All of the lights added to this scene
  23906. * @see http://doc.babylonjs.com/babylon101/lights
  23907. */
  23908. this.lights = new Array();
  23909. /**
  23910. * All of the (abstract) meshes added to this scene
  23911. */
  23912. this.meshes = new Array();
  23913. /**
  23914. * The list of skeletons added to the scene
  23915. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23916. */
  23917. this.skeletons = new Array();
  23918. /**
  23919. * All of the particle systems added to this scene
  23920. * @see http://doc.babylonjs.com/babylon101/particles
  23921. */
  23922. this.particleSystems = new Array();
  23923. /**
  23924. * Gets a list of Animations associated with the scene
  23925. */
  23926. this.animations = [];
  23927. /**
  23928. * All of the animation groups added to this scene
  23929. * @see http://doc.babylonjs.com/how_to/group
  23930. */
  23931. this.animationGroups = new Array();
  23932. /**
  23933. * All of the multi-materials added to this scene
  23934. * @see http://doc.babylonjs.com/how_to/multi_materials
  23935. */
  23936. this.multiMaterials = new Array();
  23937. /**
  23938. * All of the materials added to this scene
  23939. * @see http://doc.babylonjs.com/babylon101/materials
  23940. */
  23941. this.materials = new Array();
  23942. /**
  23943. * The list of morph target managers added to the scene
  23944. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23945. */
  23946. this.morphTargetManagers = new Array();
  23947. /**
  23948. * The list of geometries used in the scene.
  23949. */
  23950. this.geometries = new Array();
  23951. /**
  23952. * All of the tranform nodes added to this scene
  23953. * @see http://doc.babylonjs.com/how_to/transformnode
  23954. */
  23955. this.transformNodes = new Array();
  23956. /**
  23957. * ActionManagers available on the scene.
  23958. */
  23959. this.actionManagers = new Array();
  23960. /**
  23961. * Sounds to keep.
  23962. */
  23963. this.sounds = new Array();
  23964. /**
  23965. * Textures to keep.
  23966. */
  23967. this.textures = new Array();
  23968. }
  23969. /**
  23970. * Adds a parser in the list of availables ones.
  23971. * @param name Defines the name of the parser
  23972. * @param parser Defines the parser to add
  23973. */
  23974. AbstractScene.AddParser = function (name, parser) {
  23975. this._BabylonFileParsers[name] = parser;
  23976. };
  23977. /**
  23978. * Parser json data and populate both a scene and its associated container object
  23979. * @param jsonData Defines the data to parse
  23980. * @param scene Defines the scene to parse the data for
  23981. * @param container Defines the container attached to the parsing sequence
  23982. * @param rootUrl Defines the root url of the data
  23983. */
  23984. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23985. for (var parserName in this._BabylonFileParsers) {
  23986. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23987. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23988. }
  23989. }
  23990. };
  23991. /**
  23992. * Stores the list of available parsers in the application.
  23993. */
  23994. AbstractScene._BabylonFileParsers = {};
  23995. return AbstractScene;
  23996. }());
  23997. BABYLON.AbstractScene = AbstractScene;
  23998. })(BABYLON || (BABYLON = {}));
  23999. //# sourceMappingURL=babylon.abstractScene.js.map
  24000. var BABYLON;
  24001. (function (BABYLON) {
  24002. /** @hidden */
  24003. var ClickInfo = /** @class */ (function () {
  24004. function ClickInfo() {
  24005. this._singleClick = false;
  24006. this._doubleClick = false;
  24007. this._hasSwiped = false;
  24008. this._ignore = false;
  24009. }
  24010. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24011. get: function () {
  24012. return this._singleClick;
  24013. },
  24014. set: function (b) {
  24015. this._singleClick = b;
  24016. },
  24017. enumerable: true,
  24018. configurable: true
  24019. });
  24020. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24021. get: function () {
  24022. return this._doubleClick;
  24023. },
  24024. set: function (b) {
  24025. this._doubleClick = b;
  24026. },
  24027. enumerable: true,
  24028. configurable: true
  24029. });
  24030. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24031. get: function () {
  24032. return this._hasSwiped;
  24033. },
  24034. set: function (b) {
  24035. this._hasSwiped = b;
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24041. get: function () {
  24042. return this._ignore;
  24043. },
  24044. set: function (b) {
  24045. this._ignore = b;
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. return ClickInfo;
  24051. }());
  24052. /**
  24053. * This class is used by the onRenderingGroupObservable
  24054. */
  24055. var RenderingGroupInfo = /** @class */ (function () {
  24056. function RenderingGroupInfo() {
  24057. }
  24058. /**
  24059. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  24060. * This stage will be fired no matter what
  24061. */
  24062. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  24063. /**
  24064. * Called before opaque object are rendered.
  24065. * This stage will be fired only if there's 3D Opaque content to render
  24066. */
  24067. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  24068. /**
  24069. * Called after the opaque objects are rendered and before the transparent ones
  24070. * This stage will be fired only if there's 3D transparent content to render
  24071. */
  24072. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  24073. /**
  24074. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  24075. * This stage will be fired no matter what
  24076. */
  24077. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24078. return RenderingGroupInfo;
  24079. }());
  24080. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24081. /**
  24082. * Represents a scene to be rendered by the engine.
  24083. * @see http://doc.babylonjs.com/features/scene
  24084. */
  24085. var Scene = /** @class */ (function (_super) {
  24086. __extends(Scene, _super);
  24087. /**
  24088. * Creates a new Scene
  24089. * @param engine defines the engine to use to render this scene
  24090. */
  24091. function Scene(engine) {
  24092. var _this = _super.call(this) || this;
  24093. // Members
  24094. /**
  24095. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24096. */
  24097. _this.autoClear = true;
  24098. /**
  24099. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24100. */
  24101. _this.autoClearDepthAndStencil = true;
  24102. /**
  24103. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24104. */
  24105. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24106. /**
  24107. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24108. */
  24109. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24110. _this._forceWireframe = false;
  24111. _this._forcePointsCloud = false;
  24112. /**
  24113. * Gets or sets a boolean indicating if animations are enabled
  24114. */
  24115. _this.animationsEnabled = true;
  24116. _this._animationPropertiesOverride = null;
  24117. /**
  24118. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24119. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24120. */
  24121. _this.useConstantAnimationDeltaTime = false;
  24122. /**
  24123. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24124. * Please note that it requires to run a ray cast through the scene on every frame
  24125. */
  24126. _this.constantlyUpdateMeshUnderPointer = false;
  24127. /**
  24128. * Defines the HTML cursor to use when hovering over interactive elements
  24129. */
  24130. _this.hoverCursor = "pointer";
  24131. /**
  24132. * Defines the HTML default cursor to use (empty by default)
  24133. */
  24134. _this.defaultCursor = "";
  24135. /**
  24136. * This is used to call preventDefault() on pointer down
  24137. * in order to block unwanted artifacts like system double clicks
  24138. */
  24139. _this.preventDefaultOnPointerDown = true;
  24140. // Metadata
  24141. /**
  24142. * Gets or sets user defined metadata
  24143. */
  24144. _this.metadata = null;
  24145. /**
  24146. * Use this array to add regular expressions used to disable offline support for specific urls
  24147. */
  24148. _this.disableOfflineSupportExceptionRules = new Array();
  24149. /**
  24150. * An event triggered when the scene is disposed.
  24151. */
  24152. _this.onDisposeObservable = new BABYLON.Observable();
  24153. _this._onDisposeObserver = null;
  24154. /**
  24155. * An event triggered before rendering the scene (right after animations and physics)
  24156. */
  24157. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24158. _this._onBeforeRenderObserver = null;
  24159. /**
  24160. * An event triggered after rendering the scene
  24161. */
  24162. _this.onAfterRenderObservable = new BABYLON.Observable();
  24163. _this._onAfterRenderObserver = null;
  24164. /**
  24165. * An event triggered before animating the scene
  24166. */
  24167. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24168. /**
  24169. * An event triggered after animations processing
  24170. */
  24171. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24172. /**
  24173. * An event triggered before draw calls are ready to be sent
  24174. */
  24175. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24176. /**
  24177. * An event triggered after draw calls have been sent
  24178. */
  24179. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24180. /**
  24181. * An event triggered when physic simulation is about to be run
  24182. */
  24183. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24184. /**
  24185. * An event triggered when physic simulation has been done
  24186. */
  24187. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24188. /**
  24189. * An event triggered when the scene is ready
  24190. */
  24191. _this.onReadyObservable = new BABYLON.Observable();
  24192. /**
  24193. * An event triggered before rendering a camera
  24194. */
  24195. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24196. _this._onBeforeCameraRenderObserver = null;
  24197. /**
  24198. * An event triggered after rendering a camera
  24199. */
  24200. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24201. _this._onAfterCameraRenderObserver = null;
  24202. /**
  24203. * An event triggered when active meshes evaluation is about to start
  24204. */
  24205. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24206. /**
  24207. * An event triggered when active meshes evaluation is done
  24208. */
  24209. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24210. /**
  24211. * An event triggered when particles rendering is about to start
  24212. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24213. */
  24214. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24215. /**
  24216. * An event triggered when particles rendering is done
  24217. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24218. */
  24219. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24220. /**
  24221. * An event triggered when sprites rendering is about to start
  24222. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24223. */
  24224. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24225. /**
  24226. * An event triggered when sprites rendering is done
  24227. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24228. */
  24229. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24230. /**
  24231. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24232. */
  24233. _this.onDataLoadedObservable = new BABYLON.Observable();
  24234. /**
  24235. * An event triggered when a camera is created
  24236. */
  24237. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24238. /**
  24239. * An event triggered when a camera is removed
  24240. */
  24241. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24242. /**
  24243. * An event triggered when a light is created
  24244. */
  24245. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24246. /**
  24247. * An event triggered when a light is removed
  24248. */
  24249. _this.onLightRemovedObservable = new BABYLON.Observable();
  24250. /**
  24251. * An event triggered when a geometry is created
  24252. */
  24253. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24254. /**
  24255. * An event triggered when a geometry is removed
  24256. */
  24257. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24258. /**
  24259. * An event triggered when a transform node is created
  24260. */
  24261. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24262. /**
  24263. * An event triggered when a transform node is removed
  24264. */
  24265. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24266. /**
  24267. * An event triggered when a mesh is created
  24268. */
  24269. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24270. /**
  24271. * An event triggered when a mesh is removed
  24272. */
  24273. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24274. /**
  24275. * An event triggered when render targets are about to be rendered
  24276. * Can happen multiple times per frame.
  24277. */
  24278. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24279. /**
  24280. * An event triggered when render targets were rendered.
  24281. * Can happen multiple times per frame.
  24282. */
  24283. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24284. /**
  24285. * An event triggered before calculating deterministic simulation step
  24286. */
  24287. _this.onBeforeStepObservable = new BABYLON.Observable();
  24288. /**
  24289. * An event triggered after calculating deterministic simulation step
  24290. */
  24291. _this.onAfterStepObservable = new BABYLON.Observable();
  24292. /**
  24293. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24294. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24295. * 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)
  24296. */
  24297. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24298. // Animations
  24299. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24300. /**
  24301. * 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).
  24302. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24303. */
  24304. _this.onPrePointerObservable = new BABYLON.Observable();
  24305. /**
  24306. * Observable event triggered each time an input event is received from the rendering canvas
  24307. */
  24308. _this.onPointerObservable = new BABYLON.Observable();
  24309. _this._meshPickProceed = false;
  24310. _this._currentPickResult = null;
  24311. _this._previousPickResult = null;
  24312. _this._totalPointersPressed = 0;
  24313. _this._doubleClickOccured = false;
  24314. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24315. _this.cameraToUseForPointers = null;
  24316. _this._pointerX = 0;
  24317. _this._pointerY = 0;
  24318. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24319. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24320. _this._startingPointerTime = 0;
  24321. _this._previousStartingPointerTime = 0;
  24322. _this._pointerCaptures = {};
  24323. // Deterministic lockstep
  24324. _this._timeAccumulator = 0;
  24325. _this._currentStepId = 0;
  24326. _this._currentInternalStep = 0;
  24327. // Keyboard
  24328. /**
  24329. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24330. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24331. */
  24332. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24333. /**
  24334. * Observable event triggered each time an keyboard event is received from the hosting window
  24335. */
  24336. _this.onKeyboardObservable = new BABYLON.Observable();
  24337. // Coordinates system
  24338. _this._useRightHandedSystem = false;
  24339. // Fog
  24340. _this._fogEnabled = true;
  24341. _this._fogMode = Scene.FOGMODE_NONE;
  24342. /**
  24343. * Gets or sets the fog color to use
  24344. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24345. */
  24346. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24347. /**
  24348. * Gets or sets the fog density to use
  24349. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24350. */
  24351. _this.fogDensity = 0.1;
  24352. /**
  24353. * Gets or sets the fog start distance to use
  24354. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24355. */
  24356. _this.fogStart = 0;
  24357. /**
  24358. * Gets or sets the fog end distance to use
  24359. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24360. */
  24361. _this.fogEnd = 1000.0;
  24362. // Lights
  24363. _this._shadowsEnabled = true;
  24364. _this._lightsEnabled = true;
  24365. /** All of the active cameras added to this scene. */
  24366. _this.activeCameras = new Array();
  24367. // Textures
  24368. _this._texturesEnabled = true;
  24369. // Particles
  24370. /**
  24371. * Gets or sets a boolean indicating if particles are enabled on this scene
  24372. */
  24373. _this.particlesEnabled = true;
  24374. // Sprites
  24375. /**
  24376. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24377. */
  24378. _this.spritesEnabled = true;
  24379. /**
  24380. * All of the sprite managers added to this scene
  24381. * @see http://doc.babylonjs.com/babylon101/sprites
  24382. */
  24383. _this.spriteManagers = new Array();
  24384. // Skeletons
  24385. _this._skeletonsEnabled = true;
  24386. // Lens flares
  24387. /**
  24388. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24389. */
  24390. _this.lensFlaresEnabled = true;
  24391. // Collisions
  24392. /**
  24393. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24394. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24395. */
  24396. _this.collisionsEnabled = true;
  24397. /**
  24398. * Defines the gravity applied to this scene (used only for collisions)
  24399. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24400. */
  24401. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24402. // Postprocesses
  24403. /**
  24404. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24405. */
  24406. _this.postProcessesEnabled = true;
  24407. /**
  24408. * The list of postprocesses added to the scene
  24409. */
  24410. _this.postProcesses = new Array();
  24411. // Customs render targets
  24412. /**
  24413. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24414. */
  24415. _this.renderTargetsEnabled = true;
  24416. /**
  24417. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24418. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24419. */
  24420. _this.dumpNextRenderTargets = false;
  24421. /**
  24422. * The list of user defined render targets added to the scene
  24423. */
  24424. _this.customRenderTargets = new Array();
  24425. /**
  24426. * Gets the list of meshes imported to the scene through SceneLoader
  24427. */
  24428. _this.importedMeshesFiles = new Array();
  24429. // Probes
  24430. /**
  24431. * Gets or sets a boolean indicating if probes are enabled on this scene
  24432. */
  24433. _this.probesEnabled = true;
  24434. /**
  24435. * The list of reflection probes added to the scene
  24436. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24437. */
  24438. _this.reflectionProbes = new Array();
  24439. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24440. // Procedural textures
  24441. /**
  24442. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24443. */
  24444. _this.proceduralTexturesEnabled = true;
  24445. /**
  24446. * The list of procedural textures added to the scene
  24447. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24448. */
  24449. _this.proceduralTextures = new Array();
  24450. /**
  24451. * The list of sound tracks added to the scene
  24452. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24453. */
  24454. _this.soundTracks = new Array();
  24455. _this._audioEnabled = true;
  24456. _this._headphone = false;
  24457. // Performance counters
  24458. _this._totalVertices = new BABYLON.PerfCounter();
  24459. /** @hidden */
  24460. _this._activeIndices = new BABYLON.PerfCounter();
  24461. /** @hidden */
  24462. _this._activeParticles = new BABYLON.PerfCounter();
  24463. /** @hidden */
  24464. _this._activeBones = new BABYLON.PerfCounter();
  24465. _this._animationTime = 0;
  24466. /**
  24467. * Gets or sets a general scale for animation speed
  24468. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24469. */
  24470. _this.animationTimeScale = 1;
  24471. _this._renderId = 0;
  24472. _this._executeWhenReadyTimeoutId = -1;
  24473. _this._intermediateRendering = false;
  24474. _this._viewUpdateFlag = -1;
  24475. _this._projectionUpdateFlag = -1;
  24476. _this._alternateViewUpdateFlag = -1;
  24477. _this._alternateProjectionUpdateFlag = -1;
  24478. /** @hidden */
  24479. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24480. _this._activeRequests = new Array();
  24481. _this._pendingData = new Array();
  24482. _this._isDisposed = false;
  24483. /**
  24484. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24485. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24486. */
  24487. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24488. _this._activeMeshes = new BABYLON.SmartArray(256);
  24489. _this._processedMaterials = new BABYLON.SmartArray(256);
  24490. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24491. /** @hidden */
  24492. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24493. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24494. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24495. /** @hidden */
  24496. _this._activeAnimatables = new Array();
  24497. _this._transformMatrix = BABYLON.Matrix.Zero();
  24498. _this._useAlternateCameraConfiguration = false;
  24499. _this._alternateRendering = false;
  24500. /**
  24501. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24502. * This is useful if there are more lights that the maximum simulteanous authorized
  24503. */
  24504. _this.requireLightSorting = false;
  24505. _this._depthRenderer = {};
  24506. /**
  24507. * Backing store of defined scene components.
  24508. */
  24509. _this._components = [];
  24510. /**
  24511. * Backing store of defined scene components.
  24512. */
  24513. _this._serializableComponents = [];
  24514. /**
  24515. * List of components to register on the next registration step.
  24516. */
  24517. _this._transientComponents = [];
  24518. /**
  24519. * Defines the actions happening during the per mesh ready checks.
  24520. */
  24521. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24522. /**
  24523. * Defines the actions happening before evaluate active mesh checks.
  24524. */
  24525. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24526. /**
  24527. * Defines the actions happening during the evaluate sub mesh checks.
  24528. */
  24529. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24530. /**
  24531. * Defines the actions happening during the active mesh stage.
  24532. */
  24533. _this._activeMeshStage = BABYLON.Stage.Create();
  24534. /**
  24535. * Defines the actions happening during the per camera render target step.
  24536. */
  24537. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24538. /**
  24539. * Defines the actions happening just before the active camera is drawing.
  24540. */
  24541. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24542. /**
  24543. * Defines the actions happening just before a rendering group is drawing.
  24544. */
  24545. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24546. /**
  24547. * Defines the actions happening just after a rendering group has been drawn.
  24548. */
  24549. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24550. /**
  24551. * Defines the actions happening just after the active camera has been drawn.
  24552. */
  24553. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24554. _this._activeMeshesFrozen = false;
  24555. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24556. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24557. _this._engine.scenes.push(_this);
  24558. _this._uid = null;
  24559. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24560. if (BABYLON.PostProcessManager) {
  24561. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24562. }
  24563. if (BABYLON.OutlineRenderer) {
  24564. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24565. }
  24566. if (BABYLON.Tools.IsWindowObjectExist()) {
  24567. _this.attachControl();
  24568. }
  24569. //simplification queue
  24570. if (BABYLON.SimplificationQueue) {
  24571. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24572. }
  24573. //collision coordinator initialization. For now legacy per default.
  24574. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24575. // Uniform Buffer
  24576. _this._createUbo();
  24577. // Default Image processing definition
  24578. if (BABYLON.ImageProcessingConfiguration) {
  24579. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24580. }
  24581. return _this;
  24582. }
  24583. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24584. /** The fog is deactivated */
  24585. get: function () {
  24586. return Scene._FOGMODE_NONE;
  24587. },
  24588. enumerable: true,
  24589. configurable: true
  24590. });
  24591. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24592. /** The fog density is following an exponential function */
  24593. get: function () {
  24594. return Scene._FOGMODE_EXP;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24600. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24601. get: function () {
  24602. return Scene._FOGMODE_EXP2;
  24603. },
  24604. enumerable: true,
  24605. configurable: true
  24606. });
  24607. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24608. /** The fog density is following a linear function. */
  24609. get: function () {
  24610. return Scene._FOGMODE_LINEAR;
  24611. },
  24612. enumerable: true,
  24613. configurable: true
  24614. });
  24615. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24616. /**
  24617. * Texture used in all pbr material as the reflection texture.
  24618. * As in the majority of the scene they are the same (exception for multi room and so on),
  24619. * this is easier to reference from here than from all the materials.
  24620. */
  24621. get: function () {
  24622. return this._environmentTexture;
  24623. },
  24624. /**
  24625. * Texture used in all pbr material as the reflection texture.
  24626. * As in the majority of the scene they are the same (exception for multi room and so on),
  24627. * this is easier to set here than in all the materials.
  24628. */
  24629. set: function (value) {
  24630. if (this._environmentTexture === value) {
  24631. return;
  24632. }
  24633. this._environmentTexture = value;
  24634. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24635. },
  24636. enumerable: true,
  24637. configurable: true
  24638. });
  24639. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24640. /**
  24641. * Default image processing configuration used either in the rendering
  24642. * Forward main pass or through the imageProcessingPostProcess if present.
  24643. * As in the majority of the scene they are the same (exception for multi camera),
  24644. * this is easier to reference from here than from all the materials and post process.
  24645. *
  24646. * No setter as we it is a shared configuration, you can set the values instead.
  24647. */
  24648. get: function () {
  24649. return this._imageProcessingConfiguration;
  24650. },
  24651. enumerable: true,
  24652. configurable: true
  24653. });
  24654. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24655. get: function () {
  24656. return this._forceWireframe;
  24657. },
  24658. /**
  24659. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24660. */
  24661. set: function (value) {
  24662. if (this._forceWireframe === value) {
  24663. return;
  24664. }
  24665. this._forceWireframe = value;
  24666. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24667. },
  24668. enumerable: true,
  24669. configurable: true
  24670. });
  24671. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24672. get: function () {
  24673. return this._forcePointsCloud;
  24674. },
  24675. /**
  24676. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24677. */
  24678. set: function (value) {
  24679. if (this._forcePointsCloud === value) {
  24680. return;
  24681. }
  24682. this._forcePointsCloud = value;
  24683. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24684. },
  24685. enumerable: true,
  24686. configurable: true
  24687. });
  24688. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24689. /**
  24690. * Gets or sets the animation properties override
  24691. */
  24692. get: function () {
  24693. return this._animationPropertiesOverride;
  24694. },
  24695. set: function (value) {
  24696. this._animationPropertiesOverride = value;
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. Object.defineProperty(Scene.prototype, "onDispose", {
  24702. /** Sets a function to be executed when this scene is disposed. */
  24703. set: function (callback) {
  24704. if (this._onDisposeObserver) {
  24705. this.onDisposeObservable.remove(this._onDisposeObserver);
  24706. }
  24707. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24708. },
  24709. enumerable: true,
  24710. configurable: true
  24711. });
  24712. Object.defineProperty(Scene.prototype, "beforeRender", {
  24713. /** Sets a function to be executed before rendering this scene */
  24714. set: function (callback) {
  24715. if (this._onBeforeRenderObserver) {
  24716. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24717. }
  24718. if (callback) {
  24719. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24720. }
  24721. },
  24722. enumerable: true,
  24723. configurable: true
  24724. });
  24725. Object.defineProperty(Scene.prototype, "afterRender", {
  24726. /** Sets a function to be executed after rendering this scene */
  24727. set: function (callback) {
  24728. if (this._onAfterRenderObserver) {
  24729. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24730. }
  24731. if (callback) {
  24732. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24733. }
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24739. /** Sets a function to be executed before rendering a camera*/
  24740. set: function (callback) {
  24741. if (this._onBeforeCameraRenderObserver) {
  24742. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24743. }
  24744. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24745. },
  24746. enumerable: true,
  24747. configurable: true
  24748. });
  24749. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24750. /** Sets a function to be executed after rendering a camera*/
  24751. set: function (callback) {
  24752. if (this._onAfterCameraRenderObserver) {
  24753. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24754. }
  24755. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24761. /**
  24762. * Gets the gamepad manager associated with the scene
  24763. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24764. */
  24765. get: function () {
  24766. if (!this._gamepadManager) {
  24767. this._gamepadManager = new BABYLON.GamepadManager(this);
  24768. }
  24769. return this._gamepadManager;
  24770. },
  24771. enumerable: true,
  24772. configurable: true
  24773. });
  24774. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24775. /**
  24776. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24777. */
  24778. get: function () {
  24779. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24785. get: function () {
  24786. return this._useRightHandedSystem;
  24787. },
  24788. /**
  24789. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24790. */
  24791. set: function (value) {
  24792. if (this._useRightHandedSystem === value) {
  24793. return;
  24794. }
  24795. this._useRightHandedSystem = value;
  24796. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24797. },
  24798. enumerable: true,
  24799. configurable: true
  24800. });
  24801. /**
  24802. * Sets the step Id used by deterministic lock step
  24803. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24804. * @param newStepId defines the step Id
  24805. */
  24806. Scene.prototype.setStepId = function (newStepId) {
  24807. this._currentStepId = newStepId;
  24808. };
  24809. ;
  24810. /**
  24811. * Gets the step Id used by deterministic lock step
  24812. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24813. * @returns the step Id
  24814. */
  24815. Scene.prototype.getStepId = function () {
  24816. return this._currentStepId;
  24817. };
  24818. ;
  24819. /**
  24820. * Gets the internal step used by deterministic lock step
  24821. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24822. * @returns the internal step
  24823. */
  24824. Scene.prototype.getInternalStep = function () {
  24825. return this._currentInternalStep;
  24826. };
  24827. ;
  24828. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24829. get: function () {
  24830. return this._fogEnabled;
  24831. },
  24832. /**
  24833. * Gets or sets a boolean indicating if fog is enabled on this scene
  24834. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24835. */
  24836. set: function (value) {
  24837. if (this._fogEnabled === value) {
  24838. return;
  24839. }
  24840. this._fogEnabled = value;
  24841. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24842. },
  24843. enumerable: true,
  24844. configurable: true
  24845. });
  24846. Object.defineProperty(Scene.prototype, "fogMode", {
  24847. get: function () {
  24848. return this._fogMode;
  24849. },
  24850. /**
  24851. * Gets or sets the fog mode to use
  24852. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24853. */
  24854. set: function (value) {
  24855. if (this._fogMode === value) {
  24856. return;
  24857. }
  24858. this._fogMode = value;
  24859. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24860. },
  24861. enumerable: true,
  24862. configurable: true
  24863. });
  24864. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24865. get: function () {
  24866. return this._shadowsEnabled;
  24867. },
  24868. /**
  24869. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24870. */
  24871. set: function (value) {
  24872. if (this._shadowsEnabled === value) {
  24873. return;
  24874. }
  24875. this._shadowsEnabled = value;
  24876. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24877. },
  24878. enumerable: true,
  24879. configurable: true
  24880. });
  24881. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24882. get: function () {
  24883. return this._lightsEnabled;
  24884. },
  24885. /**
  24886. * Gets or sets a boolean indicating if lights are enabled on this scene
  24887. */
  24888. set: function (value) {
  24889. if (this._lightsEnabled === value) {
  24890. return;
  24891. }
  24892. this._lightsEnabled = value;
  24893. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24894. },
  24895. enumerable: true,
  24896. configurable: true
  24897. });
  24898. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24899. /** The default material used on meshes when no material is affected */
  24900. get: function () {
  24901. if (!this._defaultMaterial) {
  24902. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24903. }
  24904. return this._defaultMaterial;
  24905. },
  24906. /** The default material used on meshes when no material is affected */
  24907. set: function (value) {
  24908. this._defaultMaterial = value;
  24909. },
  24910. enumerable: true,
  24911. configurable: true
  24912. });
  24913. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24914. get: function () {
  24915. return this._texturesEnabled;
  24916. },
  24917. /**
  24918. * Gets or sets a boolean indicating if textures are enabled on this scene
  24919. */
  24920. set: function (value) {
  24921. if (this._texturesEnabled === value) {
  24922. return;
  24923. }
  24924. this._texturesEnabled = value;
  24925. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24926. },
  24927. enumerable: true,
  24928. configurable: true
  24929. });
  24930. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24931. get: function () {
  24932. return this._skeletonsEnabled;
  24933. },
  24934. /**
  24935. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24936. */
  24937. set: function (value) {
  24938. if (this._skeletonsEnabled === value) {
  24939. return;
  24940. }
  24941. this._skeletonsEnabled = value;
  24942. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24943. },
  24944. enumerable: true,
  24945. configurable: true
  24946. });
  24947. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24948. /**
  24949. * Gets the postprocess render pipeline manager
  24950. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24951. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24952. */
  24953. get: function () {
  24954. if (!this._postProcessRenderPipelineManager) {
  24955. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24956. }
  24957. return this._postProcessRenderPipelineManager;
  24958. },
  24959. enumerable: true,
  24960. configurable: true
  24961. });
  24962. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24963. /**
  24964. * Gets the main soundtrack associated with the scene
  24965. */
  24966. get: function () {
  24967. if (!this._mainSoundTrack) {
  24968. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24969. }
  24970. return this._mainSoundTrack;
  24971. },
  24972. enumerable: true,
  24973. configurable: true
  24974. });
  24975. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24976. /** @hidden */
  24977. get: function () {
  24978. return this._alternateRendering;
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24984. /**
  24985. * Gets the list of frustum planes (built from the active camera)
  24986. */
  24987. get: function () {
  24988. return this._frustumPlanes;
  24989. },
  24990. enumerable: true,
  24991. configurable: true
  24992. });
  24993. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24994. /**
  24995. * Gets the current geometry buffer associated to the scene.
  24996. */
  24997. get: function () {
  24998. return this._geometryBufferRenderer;
  24999. },
  25000. /**
  25001. * Sets the current geometry buffer for the scene.
  25002. */
  25003. set: function (geometryBufferRenderer) {
  25004. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  25005. this._geometryBufferRenderer = geometryBufferRenderer;
  25006. }
  25007. },
  25008. enumerable: true,
  25009. configurable: true
  25010. });
  25011. /**
  25012. * Registers the transient components if needed.
  25013. */
  25014. Scene.prototype._registerTransientComponents = function () {
  25015. // Register components that have been associated lately to the scene.
  25016. if (this._transientComponents.length > 0) {
  25017. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25018. var component = _a[_i];
  25019. component.register();
  25020. }
  25021. this._transientComponents = [];
  25022. }
  25023. };
  25024. /**
  25025. * Add a component to the scene.
  25026. * Note that the ccomponent could be registered on th next frame if this is called after
  25027. * the register component stage.
  25028. * @param component Defines the component to add to the scene
  25029. */
  25030. Scene.prototype._addComponent = function (component) {
  25031. this._components.push(component);
  25032. this._transientComponents.push(component);
  25033. var serializableComponent = component;
  25034. if (serializableComponent.addFromContainer) {
  25035. this._serializableComponents.push(serializableComponent);
  25036. }
  25037. };
  25038. /**
  25039. * Gets a component from the scene.
  25040. * @param name defines the name of the component to retrieve
  25041. * @returns the component or null if not present
  25042. */
  25043. Scene.prototype._getComponent = function (name) {
  25044. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25045. var component = _a[_i];
  25046. if (component.name === name) {
  25047. return component;
  25048. }
  25049. }
  25050. return null;
  25051. };
  25052. Object.defineProperty(Scene.prototype, "debugLayer", {
  25053. /**
  25054. * Gets the debug layer (aka Inspector) associated with the scene
  25055. * @see http://doc.babylonjs.com/features/playground_debuglayer
  25056. */
  25057. get: function () {
  25058. if (!this._debugLayer) {
  25059. this._debugLayer = new BABYLON.DebugLayer(this);
  25060. }
  25061. return this._debugLayer;
  25062. },
  25063. enumerable: true,
  25064. configurable: true
  25065. });
  25066. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25067. /**
  25068. * Gets a boolean indicating if collisions are processed on a web worker
  25069. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25070. */
  25071. get: function () {
  25072. return this._workerCollisions;
  25073. },
  25074. set: function (enabled) {
  25075. if (!BABYLON.CollisionCoordinatorLegacy) {
  25076. return;
  25077. }
  25078. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25079. this._workerCollisions = enabled;
  25080. if (this.collisionCoordinator) {
  25081. this.collisionCoordinator.destroy();
  25082. }
  25083. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25084. this.collisionCoordinator.init(this);
  25085. },
  25086. enumerable: true,
  25087. configurable: true
  25088. });
  25089. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25090. /**
  25091. * Gets the octree used to boost mesh selection (picking)
  25092. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25093. */
  25094. get: function () {
  25095. return this._selectionOctree;
  25096. },
  25097. enumerable: true,
  25098. configurable: true
  25099. });
  25100. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25101. /**
  25102. * Gets the mesh that is currently under the pointer
  25103. */
  25104. get: function () {
  25105. return this._pointerOverMesh;
  25106. },
  25107. enumerable: true,
  25108. configurable: true
  25109. });
  25110. Object.defineProperty(Scene.prototype, "pointerX", {
  25111. /**
  25112. * Gets the current on-screen X position of the pointer
  25113. */
  25114. get: function () {
  25115. return this._pointerX;
  25116. },
  25117. enumerable: true,
  25118. configurable: true
  25119. });
  25120. Object.defineProperty(Scene.prototype, "pointerY", {
  25121. /**
  25122. * Gets the current on-screen Y position of the pointer
  25123. */
  25124. get: function () {
  25125. return this._pointerY;
  25126. },
  25127. enumerable: true,
  25128. configurable: true
  25129. });
  25130. /**
  25131. * Gets the cached material (ie. the latest rendered one)
  25132. * @returns the cached material
  25133. */
  25134. Scene.prototype.getCachedMaterial = function () {
  25135. return this._cachedMaterial;
  25136. };
  25137. /**
  25138. * Gets the cached effect (ie. the latest rendered one)
  25139. * @returns the cached effect
  25140. */
  25141. Scene.prototype.getCachedEffect = function () {
  25142. return this._cachedEffect;
  25143. };
  25144. /**
  25145. * Gets the cached visibility state (ie. the latest rendered one)
  25146. * @returns the cached visibility state
  25147. */
  25148. Scene.prototype.getCachedVisibility = function () {
  25149. return this._cachedVisibility;
  25150. };
  25151. /**
  25152. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25153. * @param material defines the current material
  25154. * @param effect defines the current effect
  25155. * @param visibility defines the current visibility state
  25156. * @returns true if one parameter is not cached
  25157. */
  25158. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25159. if (visibility === void 0) { visibility = 1; }
  25160. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25161. };
  25162. /**
  25163. * Gets the outline renderer associated with the scene
  25164. * @returns a OutlineRenderer
  25165. */
  25166. Scene.prototype.getOutlineRenderer = function () {
  25167. return this._outlineRenderer;
  25168. };
  25169. /**
  25170. * Gets the engine associated with the scene
  25171. * @returns an Engine
  25172. */
  25173. Scene.prototype.getEngine = function () {
  25174. return this._engine;
  25175. };
  25176. /**
  25177. * Gets the total number of vertices rendered per frame
  25178. * @returns the total number of vertices rendered per frame
  25179. */
  25180. Scene.prototype.getTotalVertices = function () {
  25181. return this._totalVertices.current;
  25182. };
  25183. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25184. /**
  25185. * Gets the performance counter for total vertices
  25186. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25187. */
  25188. get: function () {
  25189. return this._totalVertices;
  25190. },
  25191. enumerable: true,
  25192. configurable: true
  25193. });
  25194. /**
  25195. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25196. * @returns the total number of active indices rendered per frame
  25197. */
  25198. Scene.prototype.getActiveIndices = function () {
  25199. return this._activeIndices.current;
  25200. };
  25201. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25202. /**
  25203. * Gets the performance counter for active indices
  25204. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25205. */
  25206. get: function () {
  25207. return this._activeIndices;
  25208. },
  25209. enumerable: true,
  25210. configurable: true
  25211. });
  25212. /**
  25213. * Gets the total number of active particles rendered per frame
  25214. * @returns the total number of active particles rendered per frame
  25215. */
  25216. Scene.prototype.getActiveParticles = function () {
  25217. return this._activeParticles.current;
  25218. };
  25219. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25220. /**
  25221. * Gets the performance counter for active particles
  25222. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25223. */
  25224. get: function () {
  25225. return this._activeParticles;
  25226. },
  25227. enumerable: true,
  25228. configurable: true
  25229. });
  25230. /**
  25231. * Gets the total number of active bones rendered per frame
  25232. * @returns the total number of active bones rendered per frame
  25233. */
  25234. Scene.prototype.getActiveBones = function () {
  25235. return this._activeBones.current;
  25236. };
  25237. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25238. /**
  25239. * Gets the performance counter for active bones
  25240. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25241. */
  25242. get: function () {
  25243. return this._activeBones;
  25244. },
  25245. enumerable: true,
  25246. configurable: true
  25247. });
  25248. /** @hidden */
  25249. Scene.prototype.getInterFramePerfCounter = function () {
  25250. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25251. return 0;
  25252. };
  25253. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25254. /** @hidden */
  25255. get: function () {
  25256. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25257. return null;
  25258. },
  25259. enumerable: true,
  25260. configurable: true
  25261. });
  25262. /** @hidden */
  25263. Scene.prototype.getLastFrameDuration = function () {
  25264. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25265. return 0;
  25266. };
  25267. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25268. /** @hidden */
  25269. get: function () {
  25270. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25271. return null;
  25272. },
  25273. enumerable: true,
  25274. configurable: true
  25275. });
  25276. /** @hidden */
  25277. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25278. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25279. return 0;
  25280. };
  25281. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25282. /** @hidden */
  25283. get: function () {
  25284. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25285. return null;
  25286. },
  25287. enumerable: true,
  25288. configurable: true
  25289. });
  25290. /**
  25291. * Gets the array of active meshes
  25292. * @returns an array of AbstractMesh
  25293. */
  25294. Scene.prototype.getActiveMeshes = function () {
  25295. return this._activeMeshes;
  25296. };
  25297. /** @hidden */
  25298. Scene.prototype.getRenderTargetsDuration = function () {
  25299. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25300. return 0;
  25301. };
  25302. /** @hidden */
  25303. Scene.prototype.getRenderDuration = function () {
  25304. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25305. return 0;
  25306. };
  25307. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25308. /** @hidden */
  25309. get: function () {
  25310. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25311. return null;
  25312. },
  25313. enumerable: true,
  25314. configurable: true
  25315. });
  25316. /** @hidden */
  25317. Scene.prototype.getParticlesDuration = function () {
  25318. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25319. return 0;
  25320. };
  25321. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25322. /** @hidden */
  25323. get: function () {
  25324. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25325. return null;
  25326. },
  25327. enumerable: true,
  25328. configurable: true
  25329. });
  25330. /** @hidden */
  25331. Scene.prototype.getSpritesDuration = function () {
  25332. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25333. return 0;
  25334. };
  25335. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25336. /** @hidden */
  25337. get: function () {
  25338. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25339. return null;
  25340. },
  25341. enumerable: true,
  25342. configurable: true
  25343. });
  25344. /**
  25345. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25346. * @returns a number
  25347. */
  25348. Scene.prototype.getAnimationRatio = function () {
  25349. return this._animationRatio;
  25350. };
  25351. /**
  25352. * Gets an unique Id for the current frame
  25353. * @returns a number
  25354. */
  25355. Scene.prototype.getRenderId = function () {
  25356. return this._renderId;
  25357. };
  25358. /** Call this function if you want to manually increment the render Id*/
  25359. Scene.prototype.incrementRenderId = function () {
  25360. this._renderId++;
  25361. };
  25362. Scene.prototype._updatePointerPosition = function (evt) {
  25363. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25364. if (!canvasRect) {
  25365. return;
  25366. }
  25367. this._pointerX = evt.clientX - canvasRect.left;
  25368. this._pointerY = evt.clientY - canvasRect.top;
  25369. this._unTranslatedPointerX = this._pointerX;
  25370. this._unTranslatedPointerY = this._pointerY;
  25371. };
  25372. Scene.prototype._createUbo = function () {
  25373. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25374. this._sceneUbo.addUniform("viewProjection", 16);
  25375. this._sceneUbo.addUniform("view", 16);
  25376. };
  25377. Scene.prototype._createAlternateUbo = function () {
  25378. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25379. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25380. this._alternateSceneUbo.addUniform("view", 16);
  25381. };
  25382. // Pointers handling
  25383. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25384. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25385. if (result) {
  25386. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25387. }
  25388. return result;
  25389. };
  25390. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25391. if (pointerInfo.pickInfo) {
  25392. if (!pointerInfo.pickInfo.ray) {
  25393. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25394. }
  25395. }
  25396. };
  25397. /**
  25398. * Use this method to simulate a pointer move on a mesh
  25399. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25400. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25401. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25402. * @returns the current scene
  25403. */
  25404. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25405. var evt = new PointerEvent("pointermove", pointerEventInit);
  25406. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25407. return this;
  25408. }
  25409. return this._processPointerMove(pickResult, evt);
  25410. };
  25411. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25412. var canvas = this._engine.getRenderingCanvas();
  25413. if (!canvas) {
  25414. return this;
  25415. }
  25416. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25417. this.setPointerOverSprite(null);
  25418. this.setPointerOverMesh(pickResult.pickedMesh);
  25419. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25420. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25421. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25422. }
  25423. else {
  25424. canvas.style.cursor = this.hoverCursor;
  25425. }
  25426. }
  25427. else {
  25428. canvas.style.cursor = this.defaultCursor;
  25429. }
  25430. }
  25431. else {
  25432. this.setPointerOverMesh(null);
  25433. // Sprites
  25434. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25435. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25436. this.setPointerOverSprite(pickResult.pickedSprite);
  25437. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25438. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25439. }
  25440. else {
  25441. canvas.style.cursor = this.hoverCursor;
  25442. }
  25443. }
  25444. else {
  25445. this.setPointerOverSprite(null);
  25446. // Restore pointer
  25447. canvas.style.cursor = this.defaultCursor;
  25448. }
  25449. }
  25450. if (pickResult) {
  25451. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25452. if (this.onPointerMove) {
  25453. this.onPointerMove(evt, pickResult, type);
  25454. }
  25455. if (this.onPointerObservable.hasObservers()) {
  25456. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25457. this._setRayOnPointerInfo(pi);
  25458. this.onPointerObservable.notifyObservers(pi, type);
  25459. }
  25460. }
  25461. return this;
  25462. };
  25463. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25464. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25465. if (pickResult) {
  25466. pi.ray = pickResult.ray;
  25467. }
  25468. this.onPrePointerObservable.notifyObservers(pi, type);
  25469. if (pi.skipOnPointerObservable) {
  25470. return true;
  25471. }
  25472. else {
  25473. return false;
  25474. }
  25475. };
  25476. /**
  25477. * Use this method to simulate a pointer down on a mesh
  25478. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25479. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25480. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25481. * @returns the current scene
  25482. */
  25483. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25484. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25485. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25486. return this;
  25487. }
  25488. return this._processPointerDown(pickResult, evt);
  25489. };
  25490. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25491. var _this = this;
  25492. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25493. this._pickedDownMesh = pickResult.pickedMesh;
  25494. var actionManager = pickResult.pickedMesh.actionManager;
  25495. if (actionManager) {
  25496. if (actionManager.hasPickTriggers) {
  25497. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25498. switch (evt.button) {
  25499. case 0:
  25500. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25501. break;
  25502. case 1:
  25503. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25504. break;
  25505. case 2:
  25506. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25507. break;
  25508. }
  25509. }
  25510. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25511. window.setTimeout(function () {
  25512. 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);
  25513. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25514. if (_this._totalPointersPressed !== 0 &&
  25515. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25516. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25517. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25518. _this._startingPointerTime = 0;
  25519. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25520. }
  25521. }
  25522. }, Scene.LongPressDelay);
  25523. }
  25524. }
  25525. }
  25526. if (pickResult) {
  25527. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25528. if (this.onPointerDown) {
  25529. this.onPointerDown(evt, pickResult, type);
  25530. }
  25531. if (this.onPointerObservable.hasObservers()) {
  25532. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25533. this._setRayOnPointerInfo(pi);
  25534. this.onPointerObservable.notifyObservers(pi, type);
  25535. }
  25536. }
  25537. return this;
  25538. };
  25539. /**
  25540. * Use this method to simulate a pointer up on a mesh
  25541. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25542. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25543. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25544. * @returns the current scene
  25545. */
  25546. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25547. var evt = new PointerEvent("pointerup", pointerEventInit);
  25548. var clickInfo = new ClickInfo();
  25549. clickInfo.singleClick = true;
  25550. clickInfo.ignore = true;
  25551. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25552. return this;
  25553. }
  25554. return this._processPointerUp(pickResult, evt, clickInfo);
  25555. };
  25556. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25557. if (pickResult && pickResult && pickResult.pickedMesh) {
  25558. this._pickedUpMesh = pickResult.pickedMesh;
  25559. if (this._pickedDownMesh === this._pickedUpMesh) {
  25560. if (this.onPointerPick) {
  25561. this.onPointerPick(evt, pickResult);
  25562. }
  25563. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25564. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25565. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25566. this._setRayOnPointerInfo(pi);
  25567. this.onPointerObservable.notifyObservers(pi, type_1);
  25568. }
  25569. }
  25570. if (pickResult.pickedMesh.actionManager) {
  25571. if (clickInfo.ignore) {
  25572. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25573. }
  25574. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25575. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25576. }
  25577. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25578. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25579. }
  25580. }
  25581. }
  25582. if (this._pickedDownMesh &&
  25583. this._pickedDownMesh.actionManager &&
  25584. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25585. this._pickedDownMesh !== this._pickedUpMesh) {
  25586. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25587. }
  25588. var type = BABYLON.PointerEventTypes.POINTERUP;
  25589. if (this.onPointerObservable.hasObservers()) {
  25590. if (!clickInfo.ignore) {
  25591. if (!clickInfo.hasSwiped) {
  25592. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25593. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25594. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25595. this._setRayOnPointerInfo(pi);
  25596. this.onPointerObservable.notifyObservers(pi, type_2);
  25597. }
  25598. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25599. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25600. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25601. this._setRayOnPointerInfo(pi);
  25602. this.onPointerObservable.notifyObservers(pi, type_3);
  25603. }
  25604. }
  25605. }
  25606. else {
  25607. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25608. this._setRayOnPointerInfo(pi);
  25609. this.onPointerObservable.notifyObservers(pi, type);
  25610. }
  25611. }
  25612. if (this.onPointerUp) {
  25613. this.onPointerUp(evt, pickResult, type);
  25614. }
  25615. return this;
  25616. };
  25617. /**
  25618. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25619. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25620. * @returns true if the pointer was captured
  25621. */
  25622. Scene.prototype.isPointerCaptured = function (pointerId) {
  25623. if (pointerId === void 0) { pointerId = 0; }
  25624. return this._pointerCaptures[pointerId];
  25625. };
  25626. /**
  25627. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25628. * @param attachUp defines if you want to attach events to pointerup
  25629. * @param attachDown defines if you want to attach events to pointerdown
  25630. * @param attachMove defines if you want to attach events to pointermove
  25631. */
  25632. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25633. var _this = this;
  25634. if (attachUp === void 0) { attachUp = true; }
  25635. if (attachDown === void 0) { attachDown = true; }
  25636. if (attachMove === void 0) { attachMove = true; }
  25637. this._initActionManager = function (act, clickInfo) {
  25638. if (!_this._meshPickProceed) {
  25639. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25640. _this._currentPickResult = pickResult;
  25641. if (pickResult) {
  25642. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25643. }
  25644. _this._meshPickProceed = true;
  25645. }
  25646. return act;
  25647. };
  25648. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25649. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25650. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25651. btn !== _this._previousButtonPressed) {
  25652. _this._doubleClickOccured = false;
  25653. clickInfo.singleClick = true;
  25654. clickInfo.ignore = false;
  25655. cb(clickInfo, _this._currentPickResult);
  25656. }
  25657. };
  25658. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25659. var clickInfo = new ClickInfo();
  25660. _this._currentPickResult = null;
  25661. var act = null;
  25662. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25663. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25664. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25665. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25666. act = _this._initActionManager(act, clickInfo);
  25667. if (act)
  25668. checkPicking = act.hasPickTriggers;
  25669. }
  25670. if (checkPicking) {
  25671. var btn = evt.button;
  25672. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25673. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25674. if (!clickInfo.hasSwiped) {
  25675. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25676. if (!checkSingleClickImmediately) {
  25677. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25678. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25679. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25680. act = _this._initActionManager(act, clickInfo);
  25681. if (act)
  25682. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25683. }
  25684. }
  25685. if (checkSingleClickImmediately) {
  25686. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25687. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25688. btn !== _this._previousButtonPressed) {
  25689. clickInfo.singleClick = true;
  25690. cb(clickInfo, _this._currentPickResult);
  25691. }
  25692. }
  25693. // at least one double click is required to be check and exclusive double click is enabled
  25694. else {
  25695. // wait that no double click has been raised during the double click delay
  25696. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25697. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25698. }
  25699. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25700. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25701. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25702. act = _this._initActionManager(act, clickInfo);
  25703. if (act)
  25704. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25705. }
  25706. if (checkDoubleClick) {
  25707. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25708. if (btn === _this._previousButtonPressed &&
  25709. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25710. !_this._doubleClickOccured) {
  25711. // pointer has not moved for 2 clicks, it's a double click
  25712. if (!clickInfo.hasSwiped &&
  25713. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25714. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25715. _this._previousStartingPointerTime = 0;
  25716. _this._doubleClickOccured = true;
  25717. clickInfo.doubleClick = true;
  25718. clickInfo.ignore = false;
  25719. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25720. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25721. }
  25722. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25723. cb(clickInfo, _this._currentPickResult);
  25724. }
  25725. // if the two successive clicks are too far, it's just two simple clicks
  25726. else {
  25727. _this._doubleClickOccured = false;
  25728. _this._previousStartingPointerTime = _this._startingPointerTime;
  25729. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25730. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25731. _this._previousButtonPressed = btn;
  25732. if (Scene.ExclusiveDoubleClickMode) {
  25733. if (_this._previousDelayedSimpleClickTimeout) {
  25734. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25735. }
  25736. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25737. cb(clickInfo, _this._previousPickResult);
  25738. }
  25739. else {
  25740. cb(clickInfo, _this._currentPickResult);
  25741. }
  25742. }
  25743. }
  25744. // just the first click of the double has been raised
  25745. else {
  25746. _this._doubleClickOccured = false;
  25747. _this._previousStartingPointerTime = _this._startingPointerTime;
  25748. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25749. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25750. _this._previousButtonPressed = btn;
  25751. }
  25752. }
  25753. }
  25754. }
  25755. clickInfo.ignore = true;
  25756. cb(clickInfo, _this._currentPickResult);
  25757. };
  25758. this._spritePredicate = function (sprite) {
  25759. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25760. };
  25761. this._onPointerMove = function (evt) {
  25762. _this._updatePointerPosition(evt);
  25763. // PreObservable support
  25764. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25765. return;
  25766. }
  25767. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25768. return;
  25769. }
  25770. if (!_this.pointerMovePredicate) {
  25771. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25772. }
  25773. // Meshes
  25774. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25775. _this._processPointerMove(pickResult, evt);
  25776. };
  25777. this._onPointerDown = function (evt) {
  25778. _this._totalPointersPressed++;
  25779. _this._pickedDownMesh = null;
  25780. _this._meshPickProceed = false;
  25781. _this._updatePointerPosition(evt);
  25782. if (_this.preventDefaultOnPointerDown && canvas) {
  25783. evt.preventDefault();
  25784. canvas.focus();
  25785. }
  25786. // PreObservable support
  25787. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25788. return;
  25789. }
  25790. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25791. return;
  25792. }
  25793. _this._pointerCaptures[evt.pointerId] = true;
  25794. _this._startingPointerPosition.x = _this._pointerX;
  25795. _this._startingPointerPosition.y = _this._pointerY;
  25796. _this._startingPointerTime = Date.now();
  25797. if (!_this.pointerDownPredicate) {
  25798. _this.pointerDownPredicate = function (mesh) {
  25799. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25800. };
  25801. }
  25802. // Meshes
  25803. _this._pickedDownMesh = null;
  25804. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25805. _this._processPointerDown(pickResult, evt);
  25806. // Sprites
  25807. _this._pickedDownSprite = null;
  25808. if (_this.spriteManagers.length > 0) {
  25809. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25810. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25811. if (pickResult.pickedSprite.actionManager) {
  25812. _this._pickedDownSprite = pickResult.pickedSprite;
  25813. switch (evt.button) {
  25814. case 0:
  25815. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25816. break;
  25817. case 1:
  25818. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25819. break;
  25820. case 2:
  25821. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25822. break;
  25823. }
  25824. if (pickResult.pickedSprite.actionManager) {
  25825. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25826. }
  25827. }
  25828. }
  25829. }
  25830. };
  25831. this._onPointerUp = function (evt) {
  25832. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25833. return; // So we need to test it the pointer down was pressed before.
  25834. }
  25835. _this._totalPointersPressed--;
  25836. _this._pickedUpMesh = null;
  25837. _this._meshPickProceed = false;
  25838. _this._updatePointerPosition(evt);
  25839. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25840. // PreObservable support
  25841. if (_this.onPrePointerObservable.hasObservers()) {
  25842. if (!clickInfo.ignore) {
  25843. if (!clickInfo.hasSwiped) {
  25844. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25845. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25846. return;
  25847. }
  25848. }
  25849. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25850. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25851. return;
  25852. }
  25853. }
  25854. }
  25855. }
  25856. else {
  25857. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25858. return;
  25859. }
  25860. }
  25861. }
  25862. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25863. return;
  25864. }
  25865. _this._pointerCaptures[evt.pointerId] = false;
  25866. if (!_this.pointerUpPredicate) {
  25867. _this.pointerUpPredicate = function (mesh) {
  25868. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25869. };
  25870. }
  25871. // Meshes
  25872. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25873. _this._initActionManager(null, clickInfo);
  25874. }
  25875. if (!pickResult) {
  25876. pickResult = _this._currentPickResult;
  25877. }
  25878. _this._processPointerUp(pickResult, evt, clickInfo);
  25879. // Sprites
  25880. if (!clickInfo.ignore) {
  25881. if (_this.spriteManagers.length > 0) {
  25882. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25883. if (spritePickResult) {
  25884. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25885. if (spritePickResult.pickedSprite.actionManager) {
  25886. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25887. if (spritePickResult.pickedSprite.actionManager) {
  25888. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25889. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25890. }
  25891. }
  25892. }
  25893. }
  25894. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25895. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25896. }
  25897. }
  25898. }
  25899. }
  25900. _this._previousPickResult = _this._currentPickResult;
  25901. });
  25902. };
  25903. this._onKeyDown = function (evt) {
  25904. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25905. if (_this.onPreKeyboardObservable.hasObservers()) {
  25906. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25907. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25908. if (pi.skipOnPointerObservable) {
  25909. return;
  25910. }
  25911. }
  25912. if (_this.onKeyboardObservable.hasObservers()) {
  25913. var pi = new BABYLON.KeyboardInfo(type, evt);
  25914. _this.onKeyboardObservable.notifyObservers(pi, type);
  25915. }
  25916. if (_this.actionManager) {
  25917. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25918. }
  25919. };
  25920. this._onKeyUp = function (evt) {
  25921. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25922. if (_this.onPreKeyboardObservable.hasObservers()) {
  25923. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25924. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25925. if (pi.skipOnPointerObservable) {
  25926. return;
  25927. }
  25928. }
  25929. if (_this.onKeyboardObservable.hasObservers()) {
  25930. var pi = new BABYLON.KeyboardInfo(type, evt);
  25931. _this.onKeyboardObservable.notifyObservers(pi, type);
  25932. }
  25933. if (_this.actionManager) {
  25934. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25935. }
  25936. };
  25937. var engine = this.getEngine();
  25938. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25939. if (!canvas) {
  25940. return;
  25941. }
  25942. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25943. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25944. });
  25945. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25946. if (!canvas) {
  25947. return;
  25948. }
  25949. canvas.removeEventListener("keydown", _this._onKeyDown);
  25950. canvas.removeEventListener("keyup", _this._onKeyUp);
  25951. });
  25952. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25953. var canvas = this._engine.getRenderingCanvas();
  25954. if (!canvas) {
  25955. return;
  25956. }
  25957. if (attachMove) {
  25958. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25959. // Wheel
  25960. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25961. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25962. }
  25963. if (attachDown) {
  25964. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25965. }
  25966. if (attachUp) {
  25967. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25968. }
  25969. canvas.tabIndex = 1;
  25970. };
  25971. /** Detaches all event handlers*/
  25972. Scene.prototype.detachControl = function () {
  25973. var engine = this.getEngine();
  25974. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25975. var canvas = engine.getRenderingCanvas();
  25976. if (!canvas) {
  25977. return;
  25978. }
  25979. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25980. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25981. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25982. if (this._onCanvasBlurObserver) {
  25983. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25984. }
  25985. if (this._onCanvasFocusObserver) {
  25986. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25987. }
  25988. // Wheel
  25989. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25990. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25991. // Keyboard
  25992. canvas.removeEventListener("keydown", this._onKeyDown);
  25993. canvas.removeEventListener("keyup", this._onKeyUp);
  25994. // Observables
  25995. this.onKeyboardObservable.clear();
  25996. this.onPreKeyboardObservable.clear();
  25997. this.onPointerObservable.clear();
  25998. this.onPrePointerObservable.clear();
  25999. };
  26000. /**
  26001. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26002. * Delay loaded resources are not taking in account
  26003. * @return true if all required resources are ready
  26004. */
  26005. Scene.prototype.isReady = function () {
  26006. if (this._isDisposed) {
  26007. return false;
  26008. }
  26009. if (this._pendingData.length > 0) {
  26010. return false;
  26011. }
  26012. var index;
  26013. var engine = this.getEngine();
  26014. // Geometries
  26015. for (index = 0; index < this.geometries.length; index++) {
  26016. var geometry = this.geometries[index];
  26017. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26018. return false;
  26019. }
  26020. }
  26021. // Meshes
  26022. for (index = 0; index < this.meshes.length; index++) {
  26023. var mesh = this.meshes[index];
  26024. if (!mesh.isEnabled()) {
  26025. continue;
  26026. }
  26027. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26028. continue;
  26029. }
  26030. if (!mesh.isReady(true)) {
  26031. return false;
  26032. }
  26033. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26034. // Is Ready For Mesh
  26035. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26036. var step = _a[_i];
  26037. if (!step.action(mesh, hardwareInstancedRendering)) {
  26038. return false;
  26039. }
  26040. }
  26041. }
  26042. // Post-processes
  26043. if (this.activeCameras && this.activeCameras.length > 0) {
  26044. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26045. var camera = _c[_b];
  26046. if (!camera.isReady(true)) {
  26047. return false;
  26048. }
  26049. }
  26050. }
  26051. else if (this.activeCamera) {
  26052. if (!this.activeCamera.isReady(true)) {
  26053. return false;
  26054. }
  26055. }
  26056. // Particles
  26057. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26058. var particleSystem = _e[_d];
  26059. if (!particleSystem.isReady()) {
  26060. return false;
  26061. }
  26062. }
  26063. return true;
  26064. };
  26065. /** Resets all cached information relative to material (including effect and visibility) */
  26066. Scene.prototype.resetCachedMaterial = function () {
  26067. this._cachedMaterial = null;
  26068. this._cachedEffect = null;
  26069. this._cachedVisibility = null;
  26070. };
  26071. /**
  26072. * Registers a function to be called before every frame render
  26073. * @param func defines the function to register
  26074. */
  26075. Scene.prototype.registerBeforeRender = function (func) {
  26076. this.onBeforeRenderObservable.add(func);
  26077. };
  26078. /**
  26079. * Unregisters a function called before every frame render
  26080. * @param func defines the function to unregister
  26081. */
  26082. Scene.prototype.unregisterBeforeRender = function (func) {
  26083. this.onBeforeRenderObservable.removeCallback(func);
  26084. };
  26085. /**
  26086. * Registers a function to be called after every frame render
  26087. * @param func defines the function to register
  26088. */
  26089. Scene.prototype.registerAfterRender = function (func) {
  26090. this.onAfterRenderObservable.add(func);
  26091. };
  26092. /**
  26093. * Unregisters a function called after every frame render
  26094. * @param func defines the function to unregister
  26095. */
  26096. Scene.prototype.unregisterAfterRender = function (func) {
  26097. this.onAfterRenderObservable.removeCallback(func);
  26098. };
  26099. Scene.prototype._executeOnceBeforeRender = function (func) {
  26100. var _this = this;
  26101. var execFunc = function () {
  26102. func();
  26103. setTimeout(function () {
  26104. _this.unregisterBeforeRender(execFunc);
  26105. });
  26106. };
  26107. this.registerBeforeRender(execFunc);
  26108. };
  26109. /**
  26110. * The provided function will run before render once and will be disposed afterwards.
  26111. * A timeout delay can be provided so that the function will be executed in N ms.
  26112. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26113. * @param func The function to be executed.
  26114. * @param timeout optional delay in ms
  26115. */
  26116. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26117. var _this = this;
  26118. if (timeout !== undefined) {
  26119. setTimeout(function () {
  26120. _this._executeOnceBeforeRender(func);
  26121. }, timeout);
  26122. }
  26123. else {
  26124. this._executeOnceBeforeRender(func);
  26125. }
  26126. };
  26127. /** @hidden */
  26128. Scene.prototype._addPendingData = function (data) {
  26129. this._pendingData.push(data);
  26130. };
  26131. /** @hidden */
  26132. Scene.prototype._removePendingData = function (data) {
  26133. var wasLoading = this.isLoading;
  26134. var index = this._pendingData.indexOf(data);
  26135. if (index !== -1) {
  26136. this._pendingData.splice(index, 1);
  26137. }
  26138. if (wasLoading && !this.isLoading) {
  26139. this.onDataLoadedObservable.notifyObservers(this);
  26140. }
  26141. };
  26142. /**
  26143. * Returns the number of items waiting to be loaded
  26144. * @returns the number of items waiting to be loaded
  26145. */
  26146. Scene.prototype.getWaitingItemsCount = function () {
  26147. return this._pendingData.length;
  26148. };
  26149. Object.defineProperty(Scene.prototype, "isLoading", {
  26150. /**
  26151. * Returns a boolean indicating if the scene is still loading data
  26152. */
  26153. get: function () {
  26154. return this._pendingData.length > 0;
  26155. },
  26156. enumerable: true,
  26157. configurable: true
  26158. });
  26159. /**
  26160. * Registers a function to be executed when the scene is ready
  26161. * @param {Function} func - the function to be executed
  26162. */
  26163. Scene.prototype.executeWhenReady = function (func) {
  26164. var _this = this;
  26165. this.onReadyObservable.add(func);
  26166. if (this._executeWhenReadyTimeoutId !== -1) {
  26167. return;
  26168. }
  26169. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26170. _this._checkIsReady();
  26171. }, 150);
  26172. };
  26173. /**
  26174. * Returns a promise that resolves when the scene is ready
  26175. * @returns A promise that resolves when the scene is ready
  26176. */
  26177. Scene.prototype.whenReadyAsync = function () {
  26178. var _this = this;
  26179. return new Promise(function (resolve) {
  26180. _this.executeWhenReady(function () {
  26181. resolve();
  26182. });
  26183. });
  26184. };
  26185. /** @hidden */
  26186. Scene.prototype._checkIsReady = function () {
  26187. var _this = this;
  26188. this._registerTransientComponents();
  26189. if (this.isReady()) {
  26190. this.onReadyObservable.notifyObservers(this);
  26191. this.onReadyObservable.clear();
  26192. this._executeWhenReadyTimeoutId = -1;
  26193. return;
  26194. }
  26195. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26196. _this._checkIsReady();
  26197. }, 150);
  26198. };
  26199. // Animations
  26200. /**
  26201. * Will start the animation sequence of a given target
  26202. * @param target defines the target
  26203. * @param from defines from which frame should animation start
  26204. * @param to defines until which frame should animation run.
  26205. * @param weight defines the weight to apply to the animation (1.0 by default)
  26206. * @param loop defines if the animation loops
  26207. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26208. * @param onAnimationEnd defines the function to be executed when the animation ends
  26209. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26210. * @returns the animatable object created for this animation
  26211. */
  26212. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26213. if (weight === void 0) { weight = 1.0; }
  26214. if (speedRatio === void 0) { speedRatio = 1.0; }
  26215. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26216. returnedAnimatable.weight = weight;
  26217. return returnedAnimatable;
  26218. };
  26219. /**
  26220. * Will start the animation sequence of a given target
  26221. * @param target defines the target
  26222. * @param from defines from which frame should animation start
  26223. * @param to defines until which frame should animation run.
  26224. * @param loop defines if the animation loops
  26225. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26226. * @param onAnimationEnd defines the function to be executed when the animation ends
  26227. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26228. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26229. * @returns the animatable object created for this animation
  26230. */
  26231. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26232. if (speedRatio === void 0) { speedRatio = 1.0; }
  26233. if (stopCurrent === void 0) { stopCurrent = true; }
  26234. if (from > to && speedRatio > 0) {
  26235. speedRatio *= -1;
  26236. }
  26237. if (stopCurrent) {
  26238. this.stopAnimation(target);
  26239. }
  26240. if (!animatable) {
  26241. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26242. }
  26243. // Local animations
  26244. if (target.animations) {
  26245. animatable.appendAnimations(target, target.animations);
  26246. }
  26247. // Children animations
  26248. if (target.getAnimatables) {
  26249. var animatables = target.getAnimatables();
  26250. for (var index = 0; index < animatables.length; index++) {
  26251. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26252. }
  26253. }
  26254. animatable.reset();
  26255. return animatable;
  26256. };
  26257. /**
  26258. * Begin a new animation on a given node
  26259. * @param target defines the target where the animation will take place
  26260. * @param animations defines the list of animations to start
  26261. * @param from defines the initial value
  26262. * @param to defines the final value
  26263. * @param loop defines if you want animation to loop (off by default)
  26264. * @param speedRatio defines the speed ratio to apply to all animations
  26265. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26266. * @returns the list of created animatables
  26267. */
  26268. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26269. if (speedRatio === undefined) {
  26270. speedRatio = 1.0;
  26271. }
  26272. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26273. return animatable;
  26274. };
  26275. /**
  26276. * Begin a new animation on a given node and its hierarchy
  26277. * @param target defines the root node where the animation will take place
  26278. * @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.
  26279. * @param animations defines the list of animations to start
  26280. * @param from defines the initial value
  26281. * @param to defines the final value
  26282. * @param loop defines if you want animation to loop (off by default)
  26283. * @param speedRatio defines the speed ratio to apply to all animations
  26284. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26285. * @returns the list of animatables created for all nodes
  26286. */
  26287. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26288. var children = target.getDescendants(directDescendantsOnly);
  26289. var result = [];
  26290. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26291. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26292. var child = children_1[_i];
  26293. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26294. }
  26295. return result;
  26296. };
  26297. /**
  26298. * Gets the animatable associated with a specific target
  26299. * @param target defines the target of the animatable
  26300. * @returns the required animatable if found
  26301. */
  26302. Scene.prototype.getAnimatableByTarget = function (target) {
  26303. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26304. if (this._activeAnimatables[index].target === target) {
  26305. return this._activeAnimatables[index];
  26306. }
  26307. }
  26308. return null;
  26309. };
  26310. /**
  26311. * Gets all animatables associated with a given target
  26312. * @param target defines the target to look animatables for
  26313. * @returns an array of Animatables
  26314. */
  26315. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26316. var result = [];
  26317. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26318. if (this._activeAnimatables[index].target === target) {
  26319. result.push(this._activeAnimatables[index]);
  26320. }
  26321. }
  26322. return result;
  26323. };
  26324. Object.defineProperty(Scene.prototype, "animatables", {
  26325. /**
  26326. * Gets all animatable attached to the scene
  26327. */
  26328. get: function () {
  26329. return this._activeAnimatables;
  26330. },
  26331. enumerable: true,
  26332. configurable: true
  26333. });
  26334. /**
  26335. * Will stop the animation of the given target
  26336. * @param target - the target
  26337. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26338. */
  26339. Scene.prototype.stopAnimation = function (target, animationName) {
  26340. var animatables = this.getAllAnimatablesByTarget(target);
  26341. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26342. var animatable = animatables_1[_i];
  26343. animatable.stop(animationName);
  26344. }
  26345. };
  26346. /**
  26347. * Stops and removes all animations that have been applied to the scene
  26348. */
  26349. Scene.prototype.stopAllAnimations = function () {
  26350. if (this._activeAnimatables) {
  26351. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26352. this._activeAnimatables[i].stop();
  26353. }
  26354. this._activeAnimatables = [];
  26355. }
  26356. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26357. var group = _a[_i];
  26358. group.stop();
  26359. }
  26360. };
  26361. Scene.prototype._animate = function () {
  26362. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26363. return;
  26364. }
  26365. // Getting time
  26366. var now = BABYLON.Tools.Now;
  26367. if (!this._animationTimeLast) {
  26368. if (this._pendingData.length > 0) {
  26369. return;
  26370. }
  26371. this._animationTimeLast = now;
  26372. }
  26373. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26374. this._animationTime += deltaTime;
  26375. this._animationTimeLast = now;
  26376. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26377. this._activeAnimatables[index]._animate(this._animationTime);
  26378. }
  26379. // Late animation bindings
  26380. this._processLateAnimationBindings();
  26381. };
  26382. /** @hidden */
  26383. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26384. var target = runtimeAnimation.target;
  26385. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26386. if (!target._lateAnimationHolders) {
  26387. target._lateAnimationHolders = {};
  26388. }
  26389. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26390. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26391. totalWeight: 0,
  26392. animations: [],
  26393. originalValue: originalValue
  26394. };
  26395. }
  26396. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26397. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26398. };
  26399. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26400. var normalizer = 1.0;
  26401. var finalPosition = BABYLON.Tmp.Vector3[0];
  26402. var finalScaling = BABYLON.Tmp.Vector3[1];
  26403. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26404. var startIndex = 0;
  26405. var originalAnimation = holder.animations[0];
  26406. var originalValue = holder.originalValue;
  26407. var scale = 1;
  26408. if (holder.totalWeight < 1.0) {
  26409. // We need to mix the original value in
  26410. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26411. scale = 1.0 - holder.totalWeight;
  26412. }
  26413. else {
  26414. startIndex = 1;
  26415. // We need to normalize the weights
  26416. normalizer = holder.totalWeight;
  26417. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26418. scale = originalAnimation.weight / normalizer;
  26419. if (scale == 1) {
  26420. return originalAnimation.currentValue;
  26421. }
  26422. }
  26423. finalScaling.scaleInPlace(scale);
  26424. finalPosition.scaleInPlace(scale);
  26425. finalQuaternion.scaleInPlace(scale);
  26426. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26427. var runtimeAnimation = holder.animations[animIndex];
  26428. var scale = runtimeAnimation.weight / normalizer;
  26429. var currentPosition = BABYLON.Tmp.Vector3[2];
  26430. var currentScaling = BABYLON.Tmp.Vector3[3];
  26431. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26432. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26433. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26434. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26435. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26436. }
  26437. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26438. return originalAnimation._workValue;
  26439. };
  26440. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26441. var originalAnimation = holder.animations[0];
  26442. var originalValue = holder.originalValue;
  26443. if (holder.animations.length === 1) {
  26444. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26445. }
  26446. var normalizer = 1.0;
  26447. var quaternions;
  26448. var weights;
  26449. if (holder.totalWeight < 1.0) {
  26450. var scale = 1.0 - holder.totalWeight;
  26451. quaternions = [];
  26452. weights = [];
  26453. quaternions.push(originalValue);
  26454. weights.push(scale);
  26455. }
  26456. else {
  26457. if (holder.animations.length === 2) { // Slerp as soon as we can
  26458. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26459. }
  26460. quaternions = [];
  26461. weights = [];
  26462. normalizer = holder.totalWeight;
  26463. }
  26464. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26465. var runtimeAnimation = holder.animations[animIndex];
  26466. quaternions.push(runtimeAnimation.currentValue);
  26467. weights.push(runtimeAnimation.weight / normalizer);
  26468. }
  26469. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26470. var cumulativeAmount = 0;
  26471. var cumulativeQuaternion = null;
  26472. for (var index = 0; index < quaternions.length;) {
  26473. if (!cumulativeQuaternion) {
  26474. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26475. cumulativeAmount = weights[index] + weights[index + 1];
  26476. index += 2;
  26477. continue;
  26478. }
  26479. cumulativeAmount += weights[index];
  26480. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26481. index++;
  26482. }
  26483. return cumulativeQuaternion;
  26484. };
  26485. Scene.prototype._processLateAnimationBindings = function () {
  26486. if (!this._registeredForLateAnimationBindings.length) {
  26487. return;
  26488. }
  26489. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26490. var target = this._registeredForLateAnimationBindings.data[index];
  26491. for (var path in target._lateAnimationHolders) {
  26492. var holder = target._lateAnimationHolders[path];
  26493. var originalAnimation = holder.animations[0];
  26494. var originalValue = holder.originalValue;
  26495. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26496. var finalValue = void 0;
  26497. if (matrixDecomposeMode) {
  26498. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26499. }
  26500. else {
  26501. var quaternionMode = originalValue.w !== undefined;
  26502. if (quaternionMode) {
  26503. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26504. }
  26505. else {
  26506. var startIndex = 0;
  26507. var normalizer = 1.0;
  26508. if (holder.totalWeight < 1.0) {
  26509. // We need to mix the original value in
  26510. if (originalValue.scale) {
  26511. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26512. }
  26513. else {
  26514. finalValue = originalValue * (1.0 - holder.totalWeight);
  26515. }
  26516. }
  26517. else {
  26518. // We need to normalize the weights
  26519. normalizer = holder.totalWeight;
  26520. var scale_1 = originalAnimation.weight / normalizer;
  26521. if (scale_1 !== 1) {
  26522. if (originalAnimation.currentValue.scale) {
  26523. finalValue = originalAnimation.currentValue.scale(scale_1);
  26524. }
  26525. else {
  26526. finalValue = originalAnimation.currentValue * scale_1;
  26527. }
  26528. }
  26529. else {
  26530. finalValue = originalAnimation.currentValue;
  26531. }
  26532. startIndex = 1;
  26533. }
  26534. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26535. var runtimeAnimation = holder.animations[animIndex];
  26536. var scale = runtimeAnimation.weight / normalizer;
  26537. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26538. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26539. }
  26540. else {
  26541. finalValue += runtimeAnimation.currentValue * scale;
  26542. }
  26543. }
  26544. }
  26545. }
  26546. target[path] = finalValue;
  26547. }
  26548. target._lateAnimationHolders = {};
  26549. }
  26550. this._registeredForLateAnimationBindings.reset();
  26551. };
  26552. // Matrix
  26553. /** @hidden */
  26554. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26555. this._useAlternateCameraConfiguration = active;
  26556. };
  26557. /**
  26558. * Gets the current view matrix
  26559. * @returns a Matrix
  26560. */
  26561. Scene.prototype.getViewMatrix = function () {
  26562. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26563. };
  26564. /**
  26565. * Gets the current projection matrix
  26566. * @returns a Matrix
  26567. */
  26568. Scene.prototype.getProjectionMatrix = function () {
  26569. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26570. };
  26571. /**
  26572. * Gets the current transform matrix
  26573. * @returns a Matrix made of View * Projection
  26574. */
  26575. Scene.prototype.getTransformMatrix = function () {
  26576. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26577. };
  26578. /**
  26579. * Sets the current transform matrix
  26580. * @param view defines the View matrix to use
  26581. * @param projection defines the Projection matrix to use
  26582. */
  26583. Scene.prototype.setTransformMatrix = function (view, projection) {
  26584. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26585. return;
  26586. }
  26587. this._viewUpdateFlag = view.updateFlag;
  26588. this._projectionUpdateFlag = projection.updateFlag;
  26589. this._viewMatrix = view;
  26590. this._projectionMatrix = projection;
  26591. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26592. // Update frustum
  26593. if (!this._frustumPlanes) {
  26594. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26595. }
  26596. else {
  26597. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26598. }
  26599. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26600. var otherCamera = this.activeCamera._alternateCamera;
  26601. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26602. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26603. }
  26604. if (this._sceneUbo.useUbo) {
  26605. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26606. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26607. this._sceneUbo.update();
  26608. }
  26609. };
  26610. /** @hidden */
  26611. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26612. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26613. return;
  26614. }
  26615. this._alternateViewUpdateFlag = view.updateFlag;
  26616. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26617. this._alternateViewMatrix = view;
  26618. this._alternateProjectionMatrix = projection;
  26619. if (!this._alternateTransformMatrix) {
  26620. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26621. }
  26622. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26623. if (!this._alternateSceneUbo) {
  26624. this._createAlternateUbo();
  26625. }
  26626. if (this._alternateSceneUbo.useUbo) {
  26627. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26628. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26629. this._alternateSceneUbo.update();
  26630. }
  26631. };
  26632. /**
  26633. * Gets the uniform buffer used to store scene data
  26634. * @returns a UniformBuffer
  26635. */
  26636. Scene.prototype.getSceneUniformBuffer = function () {
  26637. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26638. };
  26639. /**
  26640. * Gets an unique (relatively to the current scene) Id
  26641. * @returns an unique number for the scene
  26642. */
  26643. Scene.prototype.getUniqueId = function () {
  26644. var result = Scene._uniqueIdCounter;
  26645. Scene._uniqueIdCounter++;
  26646. return result;
  26647. };
  26648. /**
  26649. * Add a mesh to the list of scene's meshes
  26650. * @param newMesh defines the mesh to add
  26651. * @param recursive if all child meshes should also be added to the scene
  26652. */
  26653. Scene.prototype.addMesh = function (newMesh, recursive) {
  26654. var _this = this;
  26655. if (recursive === void 0) { recursive = false; }
  26656. this.meshes.push(newMesh);
  26657. //notify the collision coordinator
  26658. if (this.collisionCoordinator) {
  26659. this.collisionCoordinator.onMeshAdded(newMesh);
  26660. }
  26661. newMesh._resyncLightSources();
  26662. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26663. if (recursive) {
  26664. newMesh.getChildMeshes().forEach(function (m) {
  26665. _this.addMesh(m);
  26666. });
  26667. }
  26668. };
  26669. /**
  26670. * Remove a mesh for the list of scene's meshes
  26671. * @param toRemove defines the mesh to remove
  26672. * @param recursive if all child meshes should also be removed from the scene
  26673. * @returns the index where the mesh was in the mesh list
  26674. */
  26675. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26676. var _this = this;
  26677. if (recursive === void 0) { recursive = false; }
  26678. var index = this.meshes.indexOf(toRemove);
  26679. if (index !== -1) {
  26680. // Remove from the scene if mesh found
  26681. this.meshes.splice(index, 1);
  26682. }
  26683. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26684. if (recursive) {
  26685. toRemove.getChildMeshes().forEach(function (m) {
  26686. _this.removeMesh(m);
  26687. });
  26688. }
  26689. return index;
  26690. };
  26691. /**
  26692. * Add a transform node to the list of scene's transform nodes
  26693. * @param newTransformNode defines the transform node to add
  26694. */
  26695. Scene.prototype.addTransformNode = function (newTransformNode) {
  26696. this.transformNodes.push(newTransformNode);
  26697. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26698. };
  26699. /**
  26700. * Remove a transform node for the list of scene's transform nodes
  26701. * @param toRemove defines the transform node to remove
  26702. * @returns the index where the transform node was in the transform node list
  26703. */
  26704. Scene.prototype.removeTransformNode = function (toRemove) {
  26705. var index = this.transformNodes.indexOf(toRemove);
  26706. if (index !== -1) {
  26707. // Remove from the scene if found
  26708. this.transformNodes.splice(index, 1);
  26709. }
  26710. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26711. return index;
  26712. };
  26713. /**
  26714. * Remove a skeleton for the list of scene's skeletons
  26715. * @param toRemove defines the skeleton to remove
  26716. * @returns the index where the skeleton was in the skeleton list
  26717. */
  26718. Scene.prototype.removeSkeleton = function (toRemove) {
  26719. var index = this.skeletons.indexOf(toRemove);
  26720. if (index !== -1) {
  26721. // Remove from the scene if found
  26722. this.skeletons.splice(index, 1);
  26723. }
  26724. return index;
  26725. };
  26726. /**
  26727. * Remove a morph target for the list of scene's morph targets
  26728. * @param toRemove defines the morph target to remove
  26729. * @returns the index where the morph target was in the morph target list
  26730. */
  26731. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26732. var index = this.morphTargetManagers.indexOf(toRemove);
  26733. if (index !== -1) {
  26734. // Remove from the scene if found
  26735. this.morphTargetManagers.splice(index, 1);
  26736. }
  26737. return index;
  26738. };
  26739. /**
  26740. * Remove a light for the list of scene's lights
  26741. * @param toRemove defines the light to remove
  26742. * @returns the index where the light was in the light list
  26743. */
  26744. Scene.prototype.removeLight = function (toRemove) {
  26745. var index = this.lights.indexOf(toRemove);
  26746. if (index !== -1) {
  26747. // Remove from meshes
  26748. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26749. var mesh = _a[_i];
  26750. mesh._removeLightSource(toRemove);
  26751. }
  26752. // Remove from the scene if mesh found
  26753. this.lights.splice(index, 1);
  26754. this.sortLightsByPriority();
  26755. }
  26756. this.onLightRemovedObservable.notifyObservers(toRemove);
  26757. return index;
  26758. };
  26759. /**
  26760. * Remove a camera for the list of scene's cameras
  26761. * @param toRemove defines the camera to remove
  26762. * @returns the index where the camera was in the camera list
  26763. */
  26764. Scene.prototype.removeCamera = function (toRemove) {
  26765. var index = this.cameras.indexOf(toRemove);
  26766. if (index !== -1) {
  26767. // Remove from the scene if mesh found
  26768. this.cameras.splice(index, 1);
  26769. }
  26770. // Remove from activeCameras
  26771. var index2 = this.activeCameras.indexOf(toRemove);
  26772. if (index2 !== -1) {
  26773. // Remove from the scene if mesh found
  26774. this.activeCameras.splice(index2, 1);
  26775. }
  26776. // Reset the activeCamera
  26777. if (this.activeCamera === toRemove) {
  26778. if (this.cameras.length > 0) {
  26779. this.activeCamera = this.cameras[0];
  26780. }
  26781. else {
  26782. this.activeCamera = null;
  26783. }
  26784. }
  26785. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26786. return index;
  26787. };
  26788. /**
  26789. * Remove a particle system for the list of scene's particle systems
  26790. * @param toRemove defines the particle system to remove
  26791. * @returns the index where the particle system was in the particle system list
  26792. */
  26793. Scene.prototype.removeParticleSystem = function (toRemove) {
  26794. var index = this.particleSystems.indexOf(toRemove);
  26795. if (index !== -1) {
  26796. this.particleSystems.splice(index, 1);
  26797. }
  26798. return index;
  26799. };
  26800. /**
  26801. * Remove a animation for the list of scene's animations
  26802. * @param toRemove defines the animation to remove
  26803. * @returns the index where the animation was in the animation list
  26804. */
  26805. Scene.prototype.removeAnimation = function (toRemove) {
  26806. var index = this.animations.indexOf(toRemove);
  26807. if (index !== -1) {
  26808. this.animations.splice(index, 1);
  26809. }
  26810. return index;
  26811. };
  26812. /**
  26813. * Removes the given animation group from this scene.
  26814. * @param toRemove The animation group to remove
  26815. * @returns The index of the removed animation group
  26816. */
  26817. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26818. var index = this.animationGroups.indexOf(toRemove);
  26819. if (index !== -1) {
  26820. this.animationGroups.splice(index, 1);
  26821. }
  26822. return index;
  26823. };
  26824. /**
  26825. * Removes the given multi-material from this scene.
  26826. * @param toRemove The multi-material to remove
  26827. * @returns The index of the removed multi-material
  26828. */
  26829. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26830. var index = this.multiMaterials.indexOf(toRemove);
  26831. if (index !== -1) {
  26832. this.multiMaterials.splice(index, 1);
  26833. }
  26834. return index;
  26835. };
  26836. /**
  26837. * Removes the given material from this scene.
  26838. * @param toRemove The material to remove
  26839. * @returns The index of the removed material
  26840. */
  26841. Scene.prototype.removeMaterial = function (toRemove) {
  26842. var index = this.materials.indexOf(toRemove);
  26843. if (index !== -1) {
  26844. this.materials.splice(index, 1);
  26845. }
  26846. return index;
  26847. };
  26848. /**
  26849. * Removes the given action manager from this scene.
  26850. * @param toRemove The action manager to remove
  26851. * @returns The index of the removed action manager
  26852. */
  26853. Scene.prototype.removeActionManager = function (toRemove) {
  26854. var index = this.actionManagers.indexOf(toRemove);
  26855. if (index !== -1) {
  26856. this.actionManagers.splice(index, 1);
  26857. }
  26858. return index;
  26859. };
  26860. /**
  26861. * Removes the given texture from this scene.
  26862. * @param toRemove The texture to remove
  26863. * @returns The index of the removed texture
  26864. */
  26865. Scene.prototype.removeTexture = function (toRemove) {
  26866. var index = this.textures.indexOf(toRemove);
  26867. if (index !== -1) {
  26868. this.textures.splice(index, 1);
  26869. }
  26870. return index;
  26871. };
  26872. /**
  26873. * Adds the given light to this scene
  26874. * @param newLight The light to add
  26875. */
  26876. Scene.prototype.addLight = function (newLight) {
  26877. this.lights.push(newLight);
  26878. this.sortLightsByPriority();
  26879. // Add light to all meshes (To support if the light is removed and then readded)
  26880. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26881. var mesh = _a[_i];
  26882. if (mesh._lightSources.indexOf(newLight) === -1) {
  26883. mesh._lightSources.push(newLight);
  26884. mesh._resyncLightSources();
  26885. }
  26886. }
  26887. this.onNewLightAddedObservable.notifyObservers(newLight);
  26888. };
  26889. /**
  26890. * Sorts the list list based on light priorities
  26891. */
  26892. Scene.prototype.sortLightsByPriority = function () {
  26893. if (this.requireLightSorting) {
  26894. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26895. }
  26896. };
  26897. /**
  26898. * Adds the given camera to this scene
  26899. * @param newCamera The camera to add
  26900. */
  26901. Scene.prototype.addCamera = function (newCamera) {
  26902. this.cameras.push(newCamera);
  26903. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26904. };
  26905. /**
  26906. * Adds the given skeleton to this scene
  26907. * @param newSkeleton The skeleton to add
  26908. */
  26909. Scene.prototype.addSkeleton = function (newSkeleton) {
  26910. this.skeletons.push(newSkeleton);
  26911. };
  26912. /**
  26913. * Adds the given particle system to this scene
  26914. * @param newParticleSystem The particle system to add
  26915. */
  26916. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26917. this.particleSystems.push(newParticleSystem);
  26918. };
  26919. /**
  26920. * Adds the given animation to this scene
  26921. * @param newAnimation The animation to add
  26922. */
  26923. Scene.prototype.addAnimation = function (newAnimation) {
  26924. this.animations.push(newAnimation);
  26925. };
  26926. /**
  26927. * Adds the given animation group to this scene.
  26928. * @param newAnimationGroup The animation group to add
  26929. */
  26930. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26931. this.animationGroups.push(newAnimationGroup);
  26932. };
  26933. /**
  26934. * Adds the given multi-material to this scene
  26935. * @param newMultiMaterial The multi-material to add
  26936. */
  26937. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26938. this.multiMaterials.push(newMultiMaterial);
  26939. };
  26940. /**
  26941. * Adds the given material to this scene
  26942. * @param newMaterial The material to add
  26943. */
  26944. Scene.prototype.addMaterial = function (newMaterial) {
  26945. this.materials.push(newMaterial);
  26946. };
  26947. /**
  26948. * Adds the given morph target to this scene
  26949. * @param newMorphTargetManager The morph target to add
  26950. */
  26951. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26952. this.morphTargetManagers.push(newMorphTargetManager);
  26953. };
  26954. /**
  26955. * Adds the given geometry to this scene
  26956. * @param newGeometry The geometry to add
  26957. */
  26958. Scene.prototype.addGeometry = function (newGeometry) {
  26959. this.geometries.push(newGeometry);
  26960. };
  26961. /**
  26962. * Adds the given action manager to this scene
  26963. * @param newActionManager The action manager to add
  26964. */
  26965. Scene.prototype.addActionManager = function (newActionManager) {
  26966. this.actionManagers.push(newActionManager);
  26967. };
  26968. /**
  26969. * Adds the given texture to this scene.
  26970. * @param newTexture The texture to add
  26971. */
  26972. Scene.prototype.addTexture = function (newTexture) {
  26973. this.textures.push(newTexture);
  26974. };
  26975. /**
  26976. * Switch active camera
  26977. * @param newCamera defines the new active camera
  26978. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26979. */
  26980. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26981. if (attachControl === void 0) { attachControl = true; }
  26982. var canvas = this._engine.getRenderingCanvas();
  26983. if (!canvas) {
  26984. return;
  26985. }
  26986. if (this.activeCamera) {
  26987. this.activeCamera.detachControl(canvas);
  26988. }
  26989. this.activeCamera = newCamera;
  26990. if (attachControl) {
  26991. newCamera.attachControl(canvas);
  26992. }
  26993. };
  26994. /**
  26995. * sets the active camera of the scene using its ID
  26996. * @param id defines the camera's ID
  26997. * @return the new active camera or null if none found.
  26998. */
  26999. Scene.prototype.setActiveCameraByID = function (id) {
  27000. var camera = this.getCameraByID(id);
  27001. if (camera) {
  27002. this.activeCamera = camera;
  27003. return camera;
  27004. }
  27005. return null;
  27006. };
  27007. /**
  27008. * sets the active camera of the scene using its name
  27009. * @param name defines the camera's name
  27010. * @returns the new active camera or null if none found.
  27011. */
  27012. Scene.prototype.setActiveCameraByName = function (name) {
  27013. var camera = this.getCameraByName(name);
  27014. if (camera) {
  27015. this.activeCamera = camera;
  27016. return camera;
  27017. }
  27018. return null;
  27019. };
  27020. /**
  27021. * get an animation group using its name
  27022. * @param name defines the material's name
  27023. * @return the animation group or null if none found.
  27024. */
  27025. Scene.prototype.getAnimationGroupByName = function (name) {
  27026. for (var index = 0; index < this.animationGroups.length; index++) {
  27027. if (this.animationGroups[index].name === name) {
  27028. return this.animationGroups[index];
  27029. }
  27030. }
  27031. return null;
  27032. };
  27033. /**
  27034. * get a material using its id
  27035. * @param id defines the material's ID
  27036. * @return the material or null if none found.
  27037. */
  27038. Scene.prototype.getMaterialByID = function (id) {
  27039. for (var index = 0; index < this.materials.length; index++) {
  27040. if (this.materials[index].id === id) {
  27041. return this.materials[index];
  27042. }
  27043. }
  27044. return null;
  27045. };
  27046. /**
  27047. * Gets a material using its name
  27048. * @param name defines the material's name
  27049. * @return the material or null if none found.
  27050. */
  27051. Scene.prototype.getMaterialByName = function (name) {
  27052. for (var index = 0; index < this.materials.length; index++) {
  27053. if (this.materials[index].name === name) {
  27054. return this.materials[index];
  27055. }
  27056. }
  27057. return null;
  27058. };
  27059. /**
  27060. * Gets a camera using its id
  27061. * @param id defines the id to look for
  27062. * @returns the camera or null if not found
  27063. */
  27064. Scene.prototype.getCameraByID = function (id) {
  27065. for (var index = 0; index < this.cameras.length; index++) {
  27066. if (this.cameras[index].id === id) {
  27067. return this.cameras[index];
  27068. }
  27069. }
  27070. return null;
  27071. };
  27072. /**
  27073. * Gets a camera using its unique id
  27074. * @param uniqueId defines the unique id to look for
  27075. * @returns the camera or null if not found
  27076. */
  27077. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27078. for (var index = 0; index < this.cameras.length; index++) {
  27079. if (this.cameras[index].uniqueId === uniqueId) {
  27080. return this.cameras[index];
  27081. }
  27082. }
  27083. return null;
  27084. };
  27085. /**
  27086. * Gets a camera using its name
  27087. * @param name defines the camera's name
  27088. * @return the camera or null if none found.
  27089. */
  27090. Scene.prototype.getCameraByName = function (name) {
  27091. for (var index = 0; index < this.cameras.length; index++) {
  27092. if (this.cameras[index].name === name) {
  27093. return this.cameras[index];
  27094. }
  27095. }
  27096. return null;
  27097. };
  27098. /**
  27099. * Gets a bone using its id
  27100. * @param id defines the bone's id
  27101. * @return the bone or null if not found
  27102. */
  27103. Scene.prototype.getBoneByID = function (id) {
  27104. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27105. var skeleton = this.skeletons[skeletonIndex];
  27106. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27107. if (skeleton.bones[boneIndex].id === id) {
  27108. return skeleton.bones[boneIndex];
  27109. }
  27110. }
  27111. }
  27112. return null;
  27113. };
  27114. /**
  27115. * Gets a bone using its id
  27116. * @param name defines the bone's name
  27117. * @return the bone or null if not found
  27118. */
  27119. Scene.prototype.getBoneByName = function (name) {
  27120. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27121. var skeleton = this.skeletons[skeletonIndex];
  27122. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27123. if (skeleton.bones[boneIndex].name === name) {
  27124. return skeleton.bones[boneIndex];
  27125. }
  27126. }
  27127. }
  27128. return null;
  27129. };
  27130. /**
  27131. * Gets a light node using its name
  27132. * @param name defines the the light's name
  27133. * @return the light or null if none found.
  27134. */
  27135. Scene.prototype.getLightByName = function (name) {
  27136. for (var index = 0; index < this.lights.length; index++) {
  27137. if (this.lights[index].name === name) {
  27138. return this.lights[index];
  27139. }
  27140. }
  27141. return null;
  27142. };
  27143. /**
  27144. * Gets a light node using its id
  27145. * @param id defines the light's id
  27146. * @return the light or null if none found.
  27147. */
  27148. Scene.prototype.getLightByID = function (id) {
  27149. for (var index = 0; index < this.lights.length; index++) {
  27150. if (this.lights[index].id === id) {
  27151. return this.lights[index];
  27152. }
  27153. }
  27154. return null;
  27155. };
  27156. /**
  27157. * Gets a light node using its scene-generated unique ID
  27158. * @param uniqueId defines the light's unique id
  27159. * @return the light or null if none found.
  27160. */
  27161. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27162. for (var index = 0; index < this.lights.length; index++) {
  27163. if (this.lights[index].uniqueId === uniqueId) {
  27164. return this.lights[index];
  27165. }
  27166. }
  27167. return null;
  27168. };
  27169. /**
  27170. * Gets a particle system by id
  27171. * @param id defines the particle system id
  27172. * @return the corresponding system or null if none found
  27173. */
  27174. Scene.prototype.getParticleSystemByID = function (id) {
  27175. for (var index = 0; index < this.particleSystems.length; index++) {
  27176. if (this.particleSystems[index].id === id) {
  27177. return this.particleSystems[index];
  27178. }
  27179. }
  27180. return null;
  27181. };
  27182. /**
  27183. * Gets a geometry using its ID
  27184. * @param id defines the geometry's id
  27185. * @return the geometry or null if none found.
  27186. */
  27187. Scene.prototype.getGeometryByID = function (id) {
  27188. for (var index = 0; index < this.geometries.length; index++) {
  27189. if (this.geometries[index].id === id) {
  27190. return this.geometries[index];
  27191. }
  27192. }
  27193. return null;
  27194. };
  27195. /**
  27196. * Add a new geometry to this scene
  27197. * @param geometry defines the geometry to be added to the scene.
  27198. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27199. * @return a boolean defining if the geometry was added or not
  27200. */
  27201. Scene.prototype.pushGeometry = function (geometry, force) {
  27202. if (!force && this.getGeometryByID(geometry.id)) {
  27203. return false;
  27204. }
  27205. this.geometries.push(geometry);
  27206. //notify the collision coordinator
  27207. if (this.collisionCoordinator) {
  27208. this.collisionCoordinator.onGeometryAdded(geometry);
  27209. }
  27210. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27211. return true;
  27212. };
  27213. /**
  27214. * Removes an existing geometry
  27215. * @param geometry defines the geometry to be removed from the scene
  27216. * @return a boolean defining if the geometry was removed or not
  27217. */
  27218. Scene.prototype.removeGeometry = function (geometry) {
  27219. var index = this.geometries.indexOf(geometry);
  27220. if (index > -1) {
  27221. this.geometries.splice(index, 1);
  27222. //notify the collision coordinator
  27223. if (this.collisionCoordinator) {
  27224. this.collisionCoordinator.onGeometryDeleted(geometry);
  27225. }
  27226. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27227. return true;
  27228. }
  27229. return false;
  27230. };
  27231. /**
  27232. * Gets the list of geometries attached to the scene
  27233. * @returns an array of Geometry
  27234. */
  27235. Scene.prototype.getGeometries = function () {
  27236. return this.geometries;
  27237. };
  27238. /**
  27239. * Gets the first added mesh found of a given ID
  27240. * @param id defines the id to search for
  27241. * @return the mesh found or null if not found at all
  27242. */
  27243. Scene.prototype.getMeshByID = function (id) {
  27244. for (var index = 0; index < this.meshes.length; index++) {
  27245. if (this.meshes[index].id === id) {
  27246. return this.meshes[index];
  27247. }
  27248. }
  27249. return null;
  27250. };
  27251. /**
  27252. * Gets a list of meshes using their id
  27253. * @param id defines the id to search for
  27254. * @returns a list of meshes
  27255. */
  27256. Scene.prototype.getMeshesByID = function (id) {
  27257. return this.meshes.filter(function (m) {
  27258. return m.id === id;
  27259. });
  27260. };
  27261. /**
  27262. * Gets the first added transform node found of a given ID
  27263. * @param id defines the id to search for
  27264. * @return the found transform node or null if not found at all.
  27265. */
  27266. Scene.prototype.getTransformNodeByID = function (id) {
  27267. for (var index = 0; index < this.transformNodes.length; index++) {
  27268. if (this.transformNodes[index].id === id) {
  27269. return this.transformNodes[index];
  27270. }
  27271. }
  27272. return null;
  27273. };
  27274. /**
  27275. * Gets a list of transform nodes using their id
  27276. * @param id defines the id to search for
  27277. * @returns a list of transform nodes
  27278. */
  27279. Scene.prototype.getTransformNodesByID = function (id) {
  27280. return this.transformNodes.filter(function (m) {
  27281. return m.id === id;
  27282. });
  27283. };
  27284. /**
  27285. * Gets a mesh with its auto-generated unique id
  27286. * @param uniqueId defines the unique id to search for
  27287. * @return the found mesh or null if not found at all.
  27288. */
  27289. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27290. for (var index = 0; index < this.meshes.length; index++) {
  27291. if (this.meshes[index].uniqueId === uniqueId) {
  27292. return this.meshes[index];
  27293. }
  27294. }
  27295. return null;
  27296. };
  27297. /**
  27298. * Gets a the last added mesh using a given id
  27299. * @param id defines the id to search for
  27300. * @return the found mesh or null if not found at all.
  27301. */
  27302. Scene.prototype.getLastMeshByID = function (id) {
  27303. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27304. if (this.meshes[index].id === id) {
  27305. return this.meshes[index];
  27306. }
  27307. }
  27308. return null;
  27309. };
  27310. /**
  27311. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27312. * @param id defines the id to search for
  27313. * @return the found node or null if not found at all
  27314. */
  27315. Scene.prototype.getLastEntryByID = function (id) {
  27316. var index;
  27317. for (index = this.meshes.length - 1; index >= 0; index--) {
  27318. if (this.meshes[index].id === id) {
  27319. return this.meshes[index];
  27320. }
  27321. }
  27322. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27323. if (this.transformNodes[index].id === id) {
  27324. return this.transformNodes[index];
  27325. }
  27326. }
  27327. for (index = this.cameras.length - 1; index >= 0; index--) {
  27328. if (this.cameras[index].id === id) {
  27329. return this.cameras[index];
  27330. }
  27331. }
  27332. for (index = this.lights.length - 1; index >= 0; index--) {
  27333. if (this.lights[index].id === id) {
  27334. return this.lights[index];
  27335. }
  27336. }
  27337. return null;
  27338. };
  27339. /**
  27340. * Gets a node (Mesh, Camera, Light) using a given id
  27341. * @param id defines the id to search for
  27342. * @return the found node or null if not found at all
  27343. */
  27344. Scene.prototype.getNodeByID = function (id) {
  27345. var mesh = this.getMeshByID(id);
  27346. if (mesh) {
  27347. return mesh;
  27348. }
  27349. var light = this.getLightByID(id);
  27350. if (light) {
  27351. return light;
  27352. }
  27353. var camera = this.getCameraByID(id);
  27354. if (camera) {
  27355. return camera;
  27356. }
  27357. var bone = this.getBoneByID(id);
  27358. return bone;
  27359. };
  27360. /**
  27361. * Gets a node (Mesh, Camera, Light) using a given name
  27362. * @param name defines the name to search for
  27363. * @return the found node or null if not found at all.
  27364. */
  27365. Scene.prototype.getNodeByName = function (name) {
  27366. var mesh = this.getMeshByName(name);
  27367. if (mesh) {
  27368. return mesh;
  27369. }
  27370. var light = this.getLightByName(name);
  27371. if (light) {
  27372. return light;
  27373. }
  27374. var camera = this.getCameraByName(name);
  27375. if (camera) {
  27376. return camera;
  27377. }
  27378. var bone = this.getBoneByName(name);
  27379. return bone;
  27380. };
  27381. /**
  27382. * Gets a mesh using a given name
  27383. * @param name defines the name to search for
  27384. * @return the found mesh or null if not found at all.
  27385. */
  27386. Scene.prototype.getMeshByName = function (name) {
  27387. for (var index = 0; index < this.meshes.length; index++) {
  27388. if (this.meshes[index].name === name) {
  27389. return this.meshes[index];
  27390. }
  27391. }
  27392. return null;
  27393. };
  27394. /**
  27395. * Gets a transform node using a given name
  27396. * @param name defines the name to search for
  27397. * @return the found transform node or null if not found at all.
  27398. */
  27399. Scene.prototype.getTransformNodeByName = function (name) {
  27400. for (var index = 0; index < this.transformNodes.length; index++) {
  27401. if (this.transformNodes[index].name === name) {
  27402. return this.transformNodes[index];
  27403. }
  27404. }
  27405. return null;
  27406. };
  27407. /**
  27408. * Gets a sound using a given name
  27409. * @param name defines the name to search for
  27410. * @return the found sound or null if not found at all.
  27411. */
  27412. Scene.prototype.getSoundByName = function (name) {
  27413. var index;
  27414. if (BABYLON.AudioEngine) {
  27415. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27416. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27417. return this.mainSoundTrack.soundCollection[index];
  27418. }
  27419. }
  27420. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27421. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27422. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27423. return this.soundTracks[sdIndex].soundCollection[index];
  27424. }
  27425. }
  27426. }
  27427. }
  27428. return null;
  27429. };
  27430. /**
  27431. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27432. * @param id defines the id to search for
  27433. * @return the found skeleton or null if not found at all.
  27434. */
  27435. Scene.prototype.getLastSkeletonByID = function (id) {
  27436. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27437. if (this.skeletons[index].id === id) {
  27438. return this.skeletons[index];
  27439. }
  27440. }
  27441. return null;
  27442. };
  27443. /**
  27444. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27445. * @param id defines the id to search for
  27446. * @return the found skeleton or null if not found at all.
  27447. */
  27448. Scene.prototype.getSkeletonById = function (id) {
  27449. for (var index = 0; index < this.skeletons.length; index++) {
  27450. if (this.skeletons[index].id === id) {
  27451. return this.skeletons[index];
  27452. }
  27453. }
  27454. return null;
  27455. };
  27456. /**
  27457. * Gets a skeleton using a given name
  27458. * @param name defines the name to search for
  27459. * @return the found skeleton or null if not found at all.
  27460. */
  27461. Scene.prototype.getSkeletonByName = function (name) {
  27462. for (var index = 0; index < this.skeletons.length; index++) {
  27463. if (this.skeletons[index].name === name) {
  27464. return this.skeletons[index];
  27465. }
  27466. }
  27467. return null;
  27468. };
  27469. /**
  27470. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27471. * @param id defines the id to search for
  27472. * @return the found morph target manager or null if not found at all.
  27473. */
  27474. Scene.prototype.getMorphTargetManagerById = function (id) {
  27475. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27476. if (this.morphTargetManagers[index].uniqueId === id) {
  27477. return this.morphTargetManagers[index];
  27478. }
  27479. }
  27480. return null;
  27481. };
  27482. /**
  27483. * Gets a boolean indicating if the given mesh is active
  27484. * @param mesh defines the mesh to look for
  27485. * @returns true if the mesh is in the active list
  27486. */
  27487. Scene.prototype.isActiveMesh = function (mesh) {
  27488. return (this._activeMeshes.indexOf(mesh) !== -1);
  27489. };
  27490. Object.defineProperty(Scene.prototype, "uid", {
  27491. /**
  27492. * Return a unique id as a string which can serve as an identifier for the scene
  27493. */
  27494. get: function () {
  27495. if (!this._uid) {
  27496. this._uid = BABYLON.Tools.RandomId();
  27497. }
  27498. return this._uid;
  27499. },
  27500. enumerable: true,
  27501. configurable: true
  27502. });
  27503. /**
  27504. * Add an externaly attached data from its key.
  27505. * This method call will fail and return false, if such key already exists.
  27506. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27507. * @param key the unique key that identifies the data
  27508. * @param data the data object to associate to the key for this Engine instance
  27509. * @return true if no such key were already present and the data was added successfully, false otherwise
  27510. */
  27511. Scene.prototype.addExternalData = function (key, data) {
  27512. if (!this._externalData) {
  27513. this._externalData = new BABYLON.StringDictionary();
  27514. }
  27515. return this._externalData.add(key, data);
  27516. };
  27517. /**
  27518. * Get an externaly attached data from its key
  27519. * @param key the unique key that identifies the data
  27520. * @return the associated data, if present (can be null), or undefined if not present
  27521. */
  27522. Scene.prototype.getExternalData = function (key) {
  27523. if (!this._externalData) {
  27524. return null;
  27525. }
  27526. return this._externalData.get(key);
  27527. };
  27528. /**
  27529. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27530. * @param key the unique key that identifies the data
  27531. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27532. * @return the associated data, can be null if the factory returned null.
  27533. */
  27534. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27535. if (!this._externalData) {
  27536. this._externalData = new BABYLON.StringDictionary();
  27537. }
  27538. return this._externalData.getOrAddWithFactory(key, factory);
  27539. };
  27540. /**
  27541. * Remove an externaly attached data from the Engine instance
  27542. * @param key the unique key that identifies the data
  27543. * @return true if the data was successfully removed, false if it doesn't exist
  27544. */
  27545. Scene.prototype.removeExternalData = function (key) {
  27546. return this._externalData.remove(key);
  27547. };
  27548. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27549. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27550. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27551. var step = _a[_i];
  27552. step.action(mesh, subMesh);
  27553. }
  27554. var material = subMesh.getMaterial();
  27555. if (material !== null && material !== undefined) {
  27556. // Render targets
  27557. if (material.getRenderTargetTextures !== undefined) {
  27558. if (this._processedMaterials.indexOf(material) === -1) {
  27559. this._processedMaterials.push(material);
  27560. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27561. }
  27562. }
  27563. // Dispatch
  27564. this._activeIndices.addCount(subMesh.indexCount, false);
  27565. this._renderingManager.dispatch(subMesh, mesh, material);
  27566. }
  27567. }
  27568. };
  27569. /**
  27570. * Clear the processed materials smart array preventing retention point in material dispose.
  27571. */
  27572. Scene.prototype.freeProcessedMaterials = function () {
  27573. this._processedMaterials.dispose();
  27574. };
  27575. /**
  27576. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27577. */
  27578. Scene.prototype.freeActiveMeshes = function () {
  27579. this._activeMeshes.dispose();
  27580. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27581. this.activeCamera._activeMeshes.dispose();
  27582. }
  27583. if (this.activeCameras) {
  27584. for (var i = 0; i < this.activeCameras.length; i++) {
  27585. var activeCamera = this.activeCameras[i];
  27586. if (activeCamera && activeCamera._activeMeshes) {
  27587. activeCamera._activeMeshes.dispose();
  27588. }
  27589. }
  27590. }
  27591. };
  27592. /**
  27593. * Clear the info related to rendering groups preventing retention points during dispose.
  27594. */
  27595. Scene.prototype.freeRenderingGroups = function () {
  27596. if (this._renderingManager) {
  27597. this._renderingManager.freeRenderingGroups();
  27598. }
  27599. if (this.textures) {
  27600. for (var i = 0; i < this.textures.length; i++) {
  27601. var texture = this.textures[i];
  27602. if (texture && texture.renderList) {
  27603. texture.freeRenderingGroups();
  27604. }
  27605. }
  27606. }
  27607. };
  27608. /** @hidden */
  27609. Scene.prototype._isInIntermediateRendering = function () {
  27610. return this._intermediateRendering;
  27611. };
  27612. /**
  27613. * Defines the current active mesh candidate provider
  27614. * @param provider defines the provider to use
  27615. */
  27616. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27617. this._activeMeshCandidateProvider = provider;
  27618. };
  27619. /**
  27620. * Gets the current active mesh candidate provider
  27621. * @returns the current active mesh candidate provider
  27622. */
  27623. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27624. return this._activeMeshCandidateProvider;
  27625. };
  27626. /**
  27627. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27628. * @returns the current scene
  27629. */
  27630. Scene.prototype.freezeActiveMeshes = function () {
  27631. if (!this.activeCamera) {
  27632. return this;
  27633. }
  27634. if (!this._frustumPlanes) {
  27635. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27636. }
  27637. this._evaluateActiveMeshes();
  27638. this._activeMeshesFrozen = true;
  27639. return this;
  27640. };
  27641. /**
  27642. * Use this function to restart evaluating active meshes on every frame
  27643. * @returns the current scene
  27644. */
  27645. Scene.prototype.unfreezeActiveMeshes = function () {
  27646. this._activeMeshesFrozen = false;
  27647. return this;
  27648. };
  27649. Scene.prototype._evaluateActiveMeshes = function () {
  27650. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27651. return;
  27652. }
  27653. if (!this.activeCamera) {
  27654. return;
  27655. }
  27656. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27657. this.activeCamera._activeMeshes.reset();
  27658. this._activeMeshes.reset();
  27659. this._renderingManager.reset();
  27660. this._processedMaterials.reset();
  27661. this._activeParticleSystems.reset();
  27662. this._activeSkeletons.reset();
  27663. this._softwareSkinnedMeshes.reset();
  27664. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27665. var step = _a[_i];
  27666. step.action();
  27667. }
  27668. // Meshes
  27669. var meshes;
  27670. var len;
  27671. var checkIsEnabled = true;
  27672. // Determine mesh candidates
  27673. if (this._activeMeshCandidateProvider !== undefined) {
  27674. // Use _activeMeshCandidateProvider
  27675. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27676. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27677. if (meshes !== undefined) {
  27678. len = meshes.length;
  27679. }
  27680. else {
  27681. len = 0;
  27682. }
  27683. }
  27684. else if (this._selectionOctree !== undefined) {
  27685. // Octree
  27686. var selection = this._selectionOctree.select(this._frustumPlanes);
  27687. meshes = selection.data;
  27688. len = selection.length;
  27689. }
  27690. else {
  27691. // Full scene traversal
  27692. len = this.meshes.length;
  27693. meshes = this.meshes;
  27694. }
  27695. // Check each mesh
  27696. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27697. mesh = meshes[meshIndex];
  27698. if (mesh.isBlocked) {
  27699. continue;
  27700. }
  27701. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27702. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27703. continue;
  27704. }
  27705. mesh.computeWorldMatrix();
  27706. // Intersections
  27707. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27708. this._meshesForIntersections.pushNoDuplicate(mesh);
  27709. }
  27710. // Switch to current LOD
  27711. meshLOD = mesh.getLOD(this.activeCamera);
  27712. if (meshLOD === undefined || meshLOD === null) {
  27713. continue;
  27714. }
  27715. mesh._preActivate();
  27716. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27717. this._activeMeshes.push(mesh);
  27718. this.activeCamera._activeMeshes.push(mesh);
  27719. mesh._activate(this._renderId);
  27720. if (meshLOD !== mesh) {
  27721. meshLOD._activate(this._renderId);
  27722. }
  27723. this._activeMesh(mesh, meshLOD);
  27724. }
  27725. }
  27726. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27727. // Particle systems
  27728. if (this.particlesEnabled) {
  27729. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27730. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27731. var particleSystem = this.particleSystems[particleIndex];
  27732. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27733. continue;
  27734. }
  27735. var emitter = particleSystem.emitter;
  27736. if (!emitter.position || emitter.isEnabled()) {
  27737. this._activeParticleSystems.push(particleSystem);
  27738. particleSystem.animate();
  27739. this._renderingManager.dispatchParticles(particleSystem);
  27740. }
  27741. }
  27742. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27743. }
  27744. };
  27745. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27746. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27747. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27748. mesh.skeleton.prepare();
  27749. }
  27750. if (!mesh.computeBonesUsingShaders) {
  27751. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27752. }
  27753. }
  27754. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27755. var step = _a[_i];
  27756. step.action(sourceMesh, mesh);
  27757. }
  27758. if (mesh !== undefined && mesh !== null
  27759. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27760. // Submeshes Octrees
  27761. var len;
  27762. var subMeshes;
  27763. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27764. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27765. len = intersections.length;
  27766. subMeshes = intersections.data;
  27767. }
  27768. else {
  27769. subMeshes = mesh.subMeshes;
  27770. len = subMeshes.length;
  27771. }
  27772. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27773. subMesh = subMeshes[subIndex];
  27774. this._evaluateSubMesh(subMesh, mesh);
  27775. }
  27776. }
  27777. };
  27778. /**
  27779. * Update the transform matrix to update from the current active camera
  27780. * @param force defines a boolean used to force the update even if cache is up to date
  27781. */
  27782. Scene.prototype.updateTransformMatrix = function (force) {
  27783. if (!this.activeCamera) {
  27784. return;
  27785. }
  27786. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27787. };
  27788. /**
  27789. * 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)
  27790. * @param alternateCamera defines the camera to use
  27791. */
  27792. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27793. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27794. };
  27795. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27796. if (camera && camera._skipRendering) {
  27797. return;
  27798. }
  27799. var engine = this._engine;
  27800. this.activeCamera = camera;
  27801. if (!this.activeCamera)
  27802. throw new Error("Active camera not set");
  27803. // Viewport
  27804. engine.setViewport(this.activeCamera.viewport);
  27805. // Camera
  27806. this.resetCachedMaterial();
  27807. this._renderId++;
  27808. this.updateTransformMatrix();
  27809. if (camera._alternateCamera) {
  27810. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27811. this._alternateRendering = true;
  27812. }
  27813. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27814. // Meshes
  27815. this._evaluateActiveMeshes();
  27816. // Software skinning
  27817. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27818. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27819. mesh.applySkeleton(mesh.skeleton);
  27820. }
  27821. // Render targets
  27822. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27823. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27824. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27825. }
  27826. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27827. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27828. }
  27829. if (this.renderTargetsEnabled) {
  27830. this._intermediateRendering = true;
  27831. if (this._renderTargets.length > 0) {
  27832. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27833. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27834. var renderTarget = this._renderTargets.data[renderIndex];
  27835. if (renderTarget._shouldRender()) {
  27836. this._renderId++;
  27837. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27838. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27839. }
  27840. }
  27841. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27842. this._renderId++;
  27843. }
  27844. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27845. var step = _a[_i];
  27846. step.action(this.activeCamera);
  27847. }
  27848. this._intermediateRendering = false;
  27849. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27850. }
  27851. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27852. // Prepare Frame
  27853. if (this.postProcessManager) {
  27854. this.postProcessManager._prepareFrame();
  27855. }
  27856. // Before Camera Draw
  27857. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27858. var step = _c[_b];
  27859. step.action(this.activeCamera);
  27860. }
  27861. // Render
  27862. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27863. this._renderingManager.render(null, null, true, true);
  27864. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27865. // After Camera Draw
  27866. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27867. var step = _e[_d];
  27868. step.action(this.activeCamera);
  27869. }
  27870. // Finalize frame
  27871. if (this.postProcessManager) {
  27872. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27873. }
  27874. // Reset some special arrays
  27875. this._renderTargets.reset();
  27876. this._alternateRendering = false;
  27877. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27878. };
  27879. Scene.prototype._processSubCameras = function (camera) {
  27880. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27881. this._renderForCamera(camera);
  27882. return;
  27883. }
  27884. // rig cameras
  27885. for (var index = 0; index < camera._rigCameras.length; index++) {
  27886. this._renderForCamera(camera._rigCameras[index], camera);
  27887. }
  27888. this.activeCamera = camera;
  27889. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27890. };
  27891. Scene.prototype._checkIntersections = function () {
  27892. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27893. var sourceMesh = this._meshesForIntersections.data[index];
  27894. if (!sourceMesh.actionManager) {
  27895. continue;
  27896. }
  27897. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27898. var action = sourceMesh.actionManager.actions[actionIndex];
  27899. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27900. var parameters = action.getTriggerParameter();
  27901. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27902. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27903. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27904. if (areIntersecting && currentIntersectionInProgress === -1) {
  27905. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27906. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27907. sourceMesh._intersectionsInProgress.push(otherMesh);
  27908. }
  27909. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27910. sourceMesh._intersectionsInProgress.push(otherMesh);
  27911. }
  27912. }
  27913. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27914. //They intersected, and now they don't.
  27915. //is this trigger an exit trigger? execute an event.
  27916. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27917. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27918. }
  27919. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27920. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27921. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27922. return otherMesh === parameterMesh;
  27923. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27924. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27925. }
  27926. }
  27927. }
  27928. }
  27929. }
  27930. };
  27931. /**
  27932. * Render the scene
  27933. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27934. */
  27935. Scene.prototype.render = function (updateCameras) {
  27936. if (updateCameras === void 0) { updateCameras = true; }
  27937. if (this.isDisposed) {
  27938. return;
  27939. }
  27940. // Register components that have been associated lately to the scene.
  27941. this._registerTransientComponents();
  27942. this._activeParticles.fetchNewFrame();
  27943. this._totalVertices.fetchNewFrame();
  27944. this._activeIndices.fetchNewFrame();
  27945. this._activeBones.fetchNewFrame();
  27946. this._meshesForIntersections.reset();
  27947. this.resetCachedMaterial();
  27948. this.onBeforeAnimationsObservable.notifyObservers(this);
  27949. // Actions
  27950. if (this.actionManager) {
  27951. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27952. }
  27953. //Simplification Queue
  27954. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27955. this.simplificationQueue.executeNext();
  27956. }
  27957. if (this._engine.isDeterministicLockStep()) {
  27958. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27959. var defaultFPS = (60.0 / 1000.0);
  27960. var defaultFrameTime = 1000 / 60; // frame time in MS
  27961. if (this._physicsEngine) {
  27962. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27963. }
  27964. var stepsTaken = 0;
  27965. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27966. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27967. internalSteps = Math.min(internalSteps, maxSubSteps);
  27968. do {
  27969. this.onBeforeStepObservable.notifyObservers(this);
  27970. // Animations
  27971. this._animationRatio = defaultFrameTime * defaultFPS;
  27972. this._animate();
  27973. this.onAfterAnimationsObservable.notifyObservers(this);
  27974. // Physics
  27975. if (this._physicsEngine) {
  27976. this.onBeforePhysicsObservable.notifyObservers(this);
  27977. this._physicsEngine._step(defaultFrameTime / 1000);
  27978. this.onAfterPhysicsObservable.notifyObservers(this);
  27979. }
  27980. this.onAfterStepObservable.notifyObservers(this);
  27981. this._currentStepId++;
  27982. stepsTaken++;
  27983. deltaTime -= defaultFrameTime;
  27984. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27985. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27986. }
  27987. else {
  27988. // Animations
  27989. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27990. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27991. this._animate();
  27992. this.onAfterAnimationsObservable.notifyObservers(this);
  27993. // Physics
  27994. if (this._physicsEngine) {
  27995. this.onBeforePhysicsObservable.notifyObservers(this);
  27996. this._physicsEngine._step(deltaTime / 1000.0);
  27997. this.onAfterPhysicsObservable.notifyObservers(this);
  27998. }
  27999. }
  28000. // update gamepad manager
  28001. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28002. this._gamepadManager._checkGamepadsStatus();
  28003. }
  28004. // Update Cameras
  28005. if (updateCameras) {
  28006. if (this.activeCameras.length > 0) {
  28007. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28008. var camera = this.activeCameras[cameraIndex];
  28009. camera.update();
  28010. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28011. // rig cameras
  28012. for (var index = 0; index < camera._rigCameras.length; index++) {
  28013. camera._rigCameras[index].update();
  28014. }
  28015. }
  28016. }
  28017. }
  28018. else if (this.activeCamera) {
  28019. this.activeCamera.update();
  28020. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28021. // rig cameras
  28022. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28023. this.activeCamera._rigCameras[index].update();
  28024. }
  28025. }
  28026. }
  28027. }
  28028. // Before render
  28029. this.onBeforeRenderObservable.notifyObservers(this);
  28030. // Customs render targets
  28031. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28032. var engine = this.getEngine();
  28033. var currentActiveCamera = this.activeCamera;
  28034. if (this.renderTargetsEnabled) {
  28035. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28036. this._intermediateRendering = true;
  28037. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28038. var renderTarget = this.customRenderTargets[customIndex];
  28039. if (renderTarget._shouldRender()) {
  28040. this._renderId++;
  28041. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28042. if (!this.activeCamera)
  28043. throw new Error("Active camera not set");
  28044. // Viewport
  28045. engine.setViewport(this.activeCamera.viewport);
  28046. // Camera
  28047. this.updateTransformMatrix();
  28048. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28049. }
  28050. }
  28051. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28052. this._intermediateRendering = false;
  28053. this._renderId++;
  28054. }
  28055. // Restore back buffer
  28056. if (this.customRenderTargets.length > 0) {
  28057. engine.restoreDefaultFramebuffer();
  28058. }
  28059. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28060. this.activeCamera = currentActiveCamera;
  28061. // Procedural textures
  28062. if (this.proceduralTexturesEnabled) {
  28063. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28064. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28065. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28066. if (proceduralTexture._shouldRender()) {
  28067. proceduralTexture.render();
  28068. }
  28069. }
  28070. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28071. }
  28072. // Clear
  28073. if (this.autoClearDepthAndStencil || this.autoClear) {
  28074. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28075. }
  28076. // Shadows
  28077. if (this.shadowsEnabled) {
  28078. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28079. var light = this.lights[lightIndex];
  28080. var shadowGenerator = light.getShadowGenerator();
  28081. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28082. var shadowMap = (shadowGenerator.getShadowMap());
  28083. if (this.textures.indexOf(shadowMap) !== -1) {
  28084. this._renderTargets.push(shadowMap);
  28085. }
  28086. }
  28087. }
  28088. }
  28089. // Depth renderer
  28090. for (var key in this._depthRenderer) {
  28091. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28092. }
  28093. // Geometry renderer
  28094. if (this._geometryBufferRenderer) {
  28095. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28096. }
  28097. // RenderPipeline
  28098. if (this._postProcessRenderPipelineManager) {
  28099. this._postProcessRenderPipelineManager.update();
  28100. }
  28101. // Multi-cameras?
  28102. if (this.activeCameras.length > 0) {
  28103. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28104. if (cameraIndex > 0) {
  28105. this._engine.clear(null, false, true, true);
  28106. }
  28107. this._processSubCameras(this.activeCameras[cameraIndex]);
  28108. }
  28109. }
  28110. else {
  28111. if (!this.activeCamera) {
  28112. throw new Error("No camera defined");
  28113. }
  28114. this._processSubCameras(this.activeCamera);
  28115. }
  28116. // Intersection checks
  28117. this._checkIntersections();
  28118. // Update the audio listener attached to the camera
  28119. if (BABYLON.AudioEngine) {
  28120. this._updateAudioParameters();
  28121. }
  28122. // After render
  28123. if (this.afterRender) {
  28124. this.afterRender();
  28125. }
  28126. this.onAfterRenderObservable.notifyObservers(this);
  28127. // Cleaning
  28128. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28129. var data = this._toBeDisposed.data[index];
  28130. if (data) {
  28131. data.dispose();
  28132. }
  28133. this._toBeDisposed[index] = null;
  28134. }
  28135. this._toBeDisposed.reset();
  28136. if (this.dumpNextRenderTargets) {
  28137. this.dumpNextRenderTargets = false;
  28138. }
  28139. this._activeBones.addCount(0, true);
  28140. this._activeIndices.addCount(0, true);
  28141. this._activeParticles.addCount(0, true);
  28142. };
  28143. Scene.prototype._updateAudioParameters = function () {
  28144. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28145. return;
  28146. }
  28147. var listeningCamera;
  28148. var audioEngine = BABYLON.Engine.audioEngine;
  28149. if (this.activeCameras.length > 0) {
  28150. listeningCamera = this.activeCameras[0];
  28151. }
  28152. else {
  28153. listeningCamera = this.activeCamera;
  28154. }
  28155. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28156. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28157. // for VR cameras
  28158. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28159. listeningCamera = listeningCamera.rigCameras[0];
  28160. }
  28161. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28162. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28163. cameraDirection.normalize();
  28164. // To avoid some errors on GearVR
  28165. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28166. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28167. }
  28168. var i;
  28169. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28170. var sound = this.mainSoundTrack.soundCollection[i];
  28171. if (sound.useCustomAttenuation) {
  28172. sound.updateDistanceFromListener();
  28173. }
  28174. }
  28175. for (i = 0; i < this.soundTracks.length; i++) {
  28176. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28177. sound = this.soundTracks[i].soundCollection[j];
  28178. if (sound.useCustomAttenuation) {
  28179. sound.updateDistanceFromListener();
  28180. }
  28181. }
  28182. }
  28183. }
  28184. };
  28185. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28186. // Audio
  28187. /**
  28188. * Gets or sets if audio support is enabled
  28189. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28190. */
  28191. get: function () {
  28192. return this._audioEnabled;
  28193. },
  28194. set: function (value) {
  28195. this._audioEnabled = value;
  28196. if (BABYLON.AudioEngine) {
  28197. if (this._audioEnabled) {
  28198. this._enableAudio();
  28199. }
  28200. else {
  28201. this._disableAudio();
  28202. }
  28203. }
  28204. },
  28205. enumerable: true,
  28206. configurable: true
  28207. });
  28208. Scene.prototype._disableAudio = function () {
  28209. var i;
  28210. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28211. this.mainSoundTrack.soundCollection[i].pause();
  28212. }
  28213. for (i = 0; i < this.soundTracks.length; i++) {
  28214. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28215. this.soundTracks[i].soundCollection[j].pause();
  28216. }
  28217. }
  28218. };
  28219. Scene.prototype._enableAudio = function () {
  28220. var i;
  28221. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28222. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28223. this.mainSoundTrack.soundCollection[i].play();
  28224. }
  28225. }
  28226. for (i = 0; i < this.soundTracks.length; i++) {
  28227. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28228. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28229. this.soundTracks[i].soundCollection[j].play();
  28230. }
  28231. }
  28232. }
  28233. };
  28234. Object.defineProperty(Scene.prototype, "headphone", {
  28235. /**
  28236. * Gets or sets if audio will be output to headphones
  28237. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28238. */
  28239. get: function () {
  28240. return this._headphone;
  28241. },
  28242. set: function (value) {
  28243. this._headphone = value;
  28244. if (BABYLON.AudioEngine) {
  28245. if (this._headphone) {
  28246. this._switchAudioModeForHeadphones();
  28247. }
  28248. else {
  28249. this._switchAudioModeForNormalSpeakers();
  28250. }
  28251. }
  28252. },
  28253. enumerable: true,
  28254. configurable: true
  28255. });
  28256. Scene.prototype._switchAudioModeForHeadphones = function () {
  28257. this.mainSoundTrack.switchPanningModelToHRTF();
  28258. for (var i = 0; i < this.soundTracks.length; i++) {
  28259. this.soundTracks[i].switchPanningModelToHRTF();
  28260. }
  28261. };
  28262. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28263. this.mainSoundTrack.switchPanningModelToEqualPower();
  28264. for (var i = 0; i < this.soundTracks.length; i++) {
  28265. this.soundTracks[i].switchPanningModelToEqualPower();
  28266. }
  28267. };
  28268. /**
  28269. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28270. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28271. * @returns the created depth renderer
  28272. */
  28273. Scene.prototype.enableDepthRenderer = function (camera) {
  28274. camera = camera || this.activeCamera;
  28275. if (!camera) {
  28276. throw "No camera available to enable depth renderer";
  28277. }
  28278. if (!this._depthRenderer[camera.id]) {
  28279. var textureType = 0;
  28280. if (this._engine.getCaps().textureHalfFloatRender) {
  28281. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28282. }
  28283. else if (this._engine.getCaps().textureFloatRender) {
  28284. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28285. }
  28286. else {
  28287. throw "Depth renderer does not support int texture type";
  28288. }
  28289. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28290. }
  28291. return this._depthRenderer[camera.id];
  28292. };
  28293. /**
  28294. * Disables a depth renderer for a given camera
  28295. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28296. */
  28297. Scene.prototype.disableDepthRenderer = function (camera) {
  28298. camera = camera || this.activeCamera;
  28299. if (!camera || !this._depthRenderer[camera.id]) {
  28300. return;
  28301. }
  28302. this._depthRenderer[camera.id].dispose();
  28303. delete this._depthRenderer[camera.id];
  28304. };
  28305. /**
  28306. * Enables a GeometryBufferRender and associates it with the scene
  28307. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28308. * @returns the GeometryBufferRenderer
  28309. */
  28310. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28311. if (ratio === void 0) { ratio = 1; }
  28312. if (this._geometryBufferRenderer) {
  28313. return this._geometryBufferRenderer;
  28314. }
  28315. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28316. if (!this._geometryBufferRenderer.isSupported) {
  28317. this._geometryBufferRenderer = null;
  28318. }
  28319. return this._geometryBufferRenderer;
  28320. };
  28321. /**
  28322. * Disables the GeometryBufferRender associated with the scene
  28323. */
  28324. Scene.prototype.disableGeometryBufferRenderer = function () {
  28325. if (!this._geometryBufferRenderer) {
  28326. return;
  28327. }
  28328. this._geometryBufferRenderer.dispose();
  28329. this._geometryBufferRenderer = null;
  28330. };
  28331. /**
  28332. * Freeze all materials
  28333. * A frozen material will not be updatable but should be faster to render
  28334. */
  28335. Scene.prototype.freezeMaterials = function () {
  28336. for (var i = 0; i < this.materials.length; i++) {
  28337. this.materials[i].freeze();
  28338. }
  28339. };
  28340. /**
  28341. * Unfreeze all materials
  28342. * A frozen material will not be updatable but should be faster to render
  28343. */
  28344. Scene.prototype.unfreezeMaterials = function () {
  28345. for (var i = 0; i < this.materials.length; i++) {
  28346. this.materials[i].unfreeze();
  28347. }
  28348. };
  28349. /**
  28350. * Releases all held ressources
  28351. */
  28352. Scene.prototype.dispose = function () {
  28353. this.beforeRender = null;
  28354. this.afterRender = null;
  28355. this.skeletons = [];
  28356. this.morphTargetManagers = [];
  28357. this._transientComponents = [];
  28358. this._isReadyForMeshStage.clear();
  28359. this._beforeEvaluateActiveMeshStage.clear();
  28360. this._evaluateSubMeshStage.clear();
  28361. this._activeMeshStage.clear();
  28362. this._cameraDrawRenderTargetStage.clear();
  28363. this._beforeCameraDrawStage.clear();
  28364. this._beforeRenderingGroupDrawStage.clear();
  28365. this._afterRenderingGroupDrawStage.clear();
  28366. this._afterCameraDrawStage.clear();
  28367. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28368. var component = _a[_i];
  28369. component.dispose();
  28370. }
  28371. this.importedMeshesFiles = new Array();
  28372. this.stopAllAnimations();
  28373. this.resetCachedMaterial();
  28374. for (var key in this._depthRenderer) {
  28375. this._depthRenderer[key].dispose();
  28376. }
  28377. if (this._gamepadManager) {
  28378. this._gamepadManager.dispose();
  28379. this._gamepadManager = null;
  28380. }
  28381. // Smart arrays
  28382. if (this.activeCamera) {
  28383. this.activeCamera._activeMeshes.dispose();
  28384. this.activeCamera = null;
  28385. }
  28386. this._activeMeshes.dispose();
  28387. this._renderingManager.dispose();
  28388. this._processedMaterials.dispose();
  28389. this._activeParticleSystems.dispose();
  28390. this._activeSkeletons.dispose();
  28391. this._softwareSkinnedMeshes.dispose();
  28392. this._renderTargets.dispose();
  28393. this._registeredForLateAnimationBindings.dispose();
  28394. this._meshesForIntersections.dispose();
  28395. this._toBeDisposed.dispose();
  28396. // Abort active requests
  28397. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28398. var request = _c[_b];
  28399. request.abort();
  28400. }
  28401. // Debug layer
  28402. if (this._debugLayer) {
  28403. this._debugLayer.hide();
  28404. }
  28405. // Events
  28406. this.onDisposeObservable.notifyObservers(this);
  28407. this.onDisposeObservable.clear();
  28408. this.onBeforeRenderObservable.clear();
  28409. this.onAfterRenderObservable.clear();
  28410. this.onBeforeRenderTargetsRenderObservable.clear();
  28411. this.onAfterRenderTargetsRenderObservable.clear();
  28412. this.onAfterStepObservable.clear();
  28413. this.onBeforeStepObservable.clear();
  28414. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28415. this.onAfterActiveMeshesEvaluationObservable.clear();
  28416. this.onBeforeParticlesRenderingObservable.clear();
  28417. this.onAfterParticlesRenderingObservable.clear();
  28418. this.onBeforeSpritesRenderingObservable.clear();
  28419. this.onAfterSpritesRenderingObservable.clear();
  28420. this.onBeforeDrawPhaseObservable.clear();
  28421. this.onAfterDrawPhaseObservable.clear();
  28422. this.onBeforePhysicsObservable.clear();
  28423. this.onAfterPhysicsObservable.clear();
  28424. this.onBeforeAnimationsObservable.clear();
  28425. this.onAfterAnimationsObservable.clear();
  28426. this.onDataLoadedObservable.clear();
  28427. this.detachControl();
  28428. // Release sounds & sounds tracks
  28429. if (BABYLON.AudioEngine) {
  28430. this.disposeSounds();
  28431. }
  28432. // VR Helper
  28433. if (this.VRHelper) {
  28434. this.VRHelper.dispose();
  28435. }
  28436. // Detach cameras
  28437. var canvas = this._engine.getRenderingCanvas();
  28438. if (canvas) {
  28439. var index;
  28440. for (index = 0; index < this.cameras.length; index++) {
  28441. this.cameras[index].detachControl(canvas);
  28442. }
  28443. }
  28444. // Release animation groups
  28445. while (this.animationGroups.length) {
  28446. this.animationGroups[0].dispose();
  28447. }
  28448. // Release lights
  28449. while (this.lights.length) {
  28450. this.lights[0].dispose();
  28451. }
  28452. // Release meshes
  28453. while (this.meshes.length) {
  28454. this.meshes[0].dispose(true);
  28455. }
  28456. while (this.transformNodes.length) {
  28457. this.removeTransformNode(this.transformNodes[0]);
  28458. }
  28459. // Release cameras
  28460. while (this.cameras.length) {
  28461. this.cameras[0].dispose();
  28462. }
  28463. // Release materials
  28464. if (this.defaultMaterial) {
  28465. this.defaultMaterial.dispose();
  28466. }
  28467. while (this.multiMaterials.length) {
  28468. this.multiMaterials[0].dispose();
  28469. }
  28470. while (this.materials.length) {
  28471. this.materials[0].dispose();
  28472. }
  28473. // Release particles
  28474. while (this.particleSystems.length) {
  28475. this.particleSystems[0].dispose();
  28476. }
  28477. // Release sprites
  28478. while (this.spriteManagers.length) {
  28479. this.spriteManagers[0].dispose();
  28480. }
  28481. // Release postProcesses
  28482. while (this.postProcesses.length) {
  28483. this.postProcesses[0].dispose();
  28484. }
  28485. // Release textures
  28486. while (this.textures.length) {
  28487. this.textures[0].dispose();
  28488. }
  28489. // Release UBO
  28490. this._sceneUbo.dispose();
  28491. if (this._alternateSceneUbo) {
  28492. this._alternateSceneUbo.dispose();
  28493. }
  28494. // Post-processes
  28495. this.postProcessManager.dispose();
  28496. if (this._postProcessRenderPipelineManager) {
  28497. this._postProcessRenderPipelineManager.dispose();
  28498. }
  28499. // Physics
  28500. if (this._physicsEngine) {
  28501. this.disablePhysicsEngine();
  28502. }
  28503. // Remove from engine
  28504. index = this._engine.scenes.indexOf(this);
  28505. if (index > -1) {
  28506. this._engine.scenes.splice(index, 1);
  28507. }
  28508. this._engine.wipeCaches(true);
  28509. this._isDisposed = true;
  28510. };
  28511. Object.defineProperty(Scene.prototype, "isDisposed", {
  28512. /**
  28513. * Gets if the scene is already disposed
  28514. */
  28515. get: function () {
  28516. return this._isDisposed;
  28517. },
  28518. enumerable: true,
  28519. configurable: true
  28520. });
  28521. /**
  28522. * Releases sounds & soundtracks
  28523. */
  28524. Scene.prototype.disposeSounds = function () {
  28525. if (!this._mainSoundTrack) {
  28526. return;
  28527. }
  28528. this.mainSoundTrack.dispose();
  28529. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28530. this.soundTracks[scIndex].dispose();
  28531. }
  28532. };
  28533. /**
  28534. * Call this function to reduce memory footprint of the scene.
  28535. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28536. */
  28537. Scene.prototype.clearCachedVertexData = function () {
  28538. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28539. var mesh = this.meshes[meshIndex];
  28540. var geometry = mesh.geometry;
  28541. if (geometry) {
  28542. geometry._indices = [];
  28543. for (var vbName in geometry._vertexBuffers) {
  28544. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28545. continue;
  28546. }
  28547. geometry._vertexBuffers[vbName]._buffer._data = null;
  28548. }
  28549. }
  28550. }
  28551. };
  28552. /**
  28553. * This function will remove the local cached buffer data from texture.
  28554. * It will save memory but will prevent the texture from being rebuilt
  28555. */
  28556. Scene.prototype.cleanCachedTextureBuffer = function () {
  28557. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28558. var baseTexture = _a[_i];
  28559. var buffer = baseTexture._buffer;
  28560. if (buffer) {
  28561. baseTexture._buffer = null;
  28562. }
  28563. }
  28564. };
  28565. // Octrees
  28566. /**
  28567. * Get the world extend vectors with an optional filter
  28568. *
  28569. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28570. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28571. */
  28572. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28573. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28574. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28575. filterPredicate = filterPredicate || (function () { return true; });
  28576. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28577. mesh.computeWorldMatrix(true);
  28578. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28579. return;
  28580. }
  28581. var boundingInfo = mesh.getBoundingInfo();
  28582. var minBox = boundingInfo.boundingBox.minimumWorld;
  28583. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28584. BABYLON.Tools.CheckExtends(minBox, min, max);
  28585. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28586. });
  28587. return {
  28588. min: min,
  28589. max: max
  28590. };
  28591. };
  28592. /**
  28593. * Creates or updates the octree used to boost selection (picking)
  28594. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28595. * @param maxCapacity defines the maximum capacity per leaf
  28596. * @param maxDepth defines the maximum depth of the octree
  28597. * @returns an octree of AbstractMesh
  28598. */
  28599. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28600. if (maxCapacity === void 0) { maxCapacity = 64; }
  28601. if (maxDepth === void 0) { maxDepth = 2; }
  28602. if (!this._selectionOctree) {
  28603. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28604. }
  28605. var worldExtends = this.getWorldExtends();
  28606. // Update octree
  28607. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28608. return this._selectionOctree;
  28609. };
  28610. // Picking
  28611. /**
  28612. * Creates a ray that can be used to pick in the scene
  28613. * @param x defines the x coordinate of the origin (on-screen)
  28614. * @param y defines the y coordinate of the origin (on-screen)
  28615. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28616. * @param camera defines the camera to use for the picking
  28617. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28618. * @returns a Ray
  28619. */
  28620. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28621. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28622. var result = BABYLON.Ray.Zero();
  28623. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28624. return result;
  28625. };
  28626. /**
  28627. * Creates a ray that can be used to pick in the scene
  28628. * @param x defines the x coordinate of the origin (on-screen)
  28629. * @param y defines the y coordinate of the origin (on-screen)
  28630. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28631. * @param result defines the ray where to store the picking ray
  28632. * @param camera defines the camera to use for the picking
  28633. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28634. * @returns the current scene
  28635. */
  28636. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28637. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28638. var engine = this._engine;
  28639. if (!camera) {
  28640. if (!this.activeCamera)
  28641. throw new Error("Active camera not set");
  28642. camera = this.activeCamera;
  28643. }
  28644. var cameraViewport = camera.viewport;
  28645. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28646. // Moving coordinates to local viewport world
  28647. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28648. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28649. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28650. return this;
  28651. };
  28652. /**
  28653. * Creates a ray that can be used to pick in the scene
  28654. * @param x defines the x coordinate of the origin (on-screen)
  28655. * @param y defines the y coordinate of the origin (on-screen)
  28656. * @param camera defines the camera to use for the picking
  28657. * @returns a Ray
  28658. */
  28659. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28660. var result = BABYLON.Ray.Zero();
  28661. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28662. return result;
  28663. };
  28664. /**
  28665. * Creates a ray that can be used to pick in the scene
  28666. * @param x defines the x coordinate of the origin (on-screen)
  28667. * @param y defines the y coordinate of the origin (on-screen)
  28668. * @param result defines the ray where to store the picking ray
  28669. * @param camera defines the camera to use for the picking
  28670. * @returns the current scene
  28671. */
  28672. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28673. if (!BABYLON.PickingInfo) {
  28674. return this;
  28675. }
  28676. var engine = this._engine;
  28677. if (!camera) {
  28678. if (!this.activeCamera)
  28679. throw new Error("Active camera not set");
  28680. camera = this.activeCamera;
  28681. }
  28682. var cameraViewport = camera.viewport;
  28683. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28684. var identity = BABYLON.Matrix.Identity();
  28685. // Moving coordinates to local viewport world
  28686. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28687. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28688. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28689. return this;
  28690. };
  28691. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28692. if (!BABYLON.PickingInfo) {
  28693. return null;
  28694. }
  28695. var pickingInfo = null;
  28696. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28697. var mesh = this.meshes[meshIndex];
  28698. if (predicate) {
  28699. if (!predicate(mesh)) {
  28700. continue;
  28701. }
  28702. }
  28703. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28704. continue;
  28705. }
  28706. var world = mesh.getWorldMatrix();
  28707. var ray = rayFunction(world);
  28708. var result = mesh.intersects(ray, fastCheck);
  28709. if (!result || !result.hit)
  28710. continue;
  28711. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28712. continue;
  28713. pickingInfo = result;
  28714. if (fastCheck) {
  28715. break;
  28716. }
  28717. }
  28718. return pickingInfo || new BABYLON.PickingInfo();
  28719. };
  28720. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28721. if (!BABYLON.PickingInfo) {
  28722. return null;
  28723. }
  28724. var pickingInfos = new Array();
  28725. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28726. var mesh = this.meshes[meshIndex];
  28727. if (predicate) {
  28728. if (!predicate(mesh)) {
  28729. continue;
  28730. }
  28731. }
  28732. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28733. continue;
  28734. }
  28735. var world = mesh.getWorldMatrix();
  28736. var ray = rayFunction(world);
  28737. var result = mesh.intersects(ray, false);
  28738. if (!result || !result.hit)
  28739. continue;
  28740. pickingInfos.push(result);
  28741. }
  28742. return pickingInfos;
  28743. };
  28744. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28745. if (!BABYLON.PickingInfo) {
  28746. return null;
  28747. }
  28748. var pickingInfo = null;
  28749. if (!camera) {
  28750. if (!this.activeCamera) {
  28751. return null;
  28752. }
  28753. camera = this.activeCamera;
  28754. }
  28755. if (this.spriteManagers.length > 0) {
  28756. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28757. var spriteManager = this.spriteManagers[spriteIndex];
  28758. if (!spriteManager.isPickable) {
  28759. continue;
  28760. }
  28761. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28762. if (!result || !result.hit)
  28763. continue;
  28764. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28765. continue;
  28766. pickingInfo = result;
  28767. if (fastCheck) {
  28768. break;
  28769. }
  28770. }
  28771. }
  28772. return pickingInfo || new BABYLON.PickingInfo();
  28773. };
  28774. /** Launch a ray to try to pick a mesh in the scene
  28775. * @param x position on screen
  28776. * @param y position on screen
  28777. * @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
  28778. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28779. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28780. * @returns a PickingInfo
  28781. */
  28782. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28783. var _this = this;
  28784. if (!BABYLON.PickingInfo) {
  28785. return null;
  28786. }
  28787. var result = this._internalPick(function (world) {
  28788. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28789. return _this._tempPickingRay;
  28790. }, predicate, fastCheck);
  28791. if (result) {
  28792. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28793. }
  28794. return result;
  28795. };
  28796. /** Launch a ray to try to pick a sprite in the scene
  28797. * @param x position on screen
  28798. * @param y position on screen
  28799. * @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
  28800. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28801. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28802. * @returns a PickingInfo
  28803. */
  28804. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28805. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28806. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28807. };
  28808. /** Use the given ray to pick a mesh in the scene
  28809. * @param ray The ray to use to pick meshes
  28810. * @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
  28811. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28812. * @returns a PickingInfo
  28813. */
  28814. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28815. var _this = this;
  28816. var result = this._internalPick(function (world) {
  28817. if (!_this._pickWithRayInverseMatrix) {
  28818. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28819. }
  28820. world.invertToRef(_this._pickWithRayInverseMatrix);
  28821. if (!_this._cachedRayForTransform) {
  28822. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28823. }
  28824. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28825. return _this._cachedRayForTransform;
  28826. }, predicate, fastCheck);
  28827. if (result) {
  28828. result.ray = ray;
  28829. }
  28830. return result;
  28831. };
  28832. /**
  28833. * Launch a ray to try to pick a mesh in the scene
  28834. * @param x X position on screen
  28835. * @param y Y position on screen
  28836. * @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
  28837. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28838. * @returns an array of PickingInfo
  28839. */
  28840. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28841. var _this = this;
  28842. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28843. };
  28844. /**
  28845. * Launch a ray to try to pick a mesh in the scene
  28846. * @param ray Ray to use
  28847. * @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
  28848. * @returns an array of PickingInfo
  28849. */
  28850. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28851. var _this = this;
  28852. return this._internalMultiPick(function (world) {
  28853. if (!_this._pickWithRayInverseMatrix) {
  28854. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28855. }
  28856. world.invertToRef(_this._pickWithRayInverseMatrix);
  28857. if (!_this._cachedRayForTransform) {
  28858. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28859. }
  28860. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28861. return _this._cachedRayForTransform;
  28862. }, predicate);
  28863. };
  28864. /**
  28865. * Force the value of meshUnderPointer
  28866. * @param mesh defines the mesh to use
  28867. */
  28868. Scene.prototype.setPointerOverMesh = function (mesh) {
  28869. if (this._pointerOverMesh === mesh) {
  28870. return;
  28871. }
  28872. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28873. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28874. }
  28875. this._pointerOverMesh = mesh;
  28876. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28877. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28878. }
  28879. };
  28880. /**
  28881. * Gets the mesh under the pointer
  28882. * @returns a Mesh or null if no mesh is under the pointer
  28883. */
  28884. Scene.prototype.getPointerOverMesh = function () {
  28885. return this._pointerOverMesh;
  28886. };
  28887. /**
  28888. * Force the sprite under the pointer
  28889. * @param sprite defines the sprite to use
  28890. */
  28891. Scene.prototype.setPointerOverSprite = function (sprite) {
  28892. if (this._pointerOverSprite === sprite) {
  28893. return;
  28894. }
  28895. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28896. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28897. }
  28898. this._pointerOverSprite = sprite;
  28899. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28900. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28901. }
  28902. };
  28903. /**
  28904. * Gets the sprite under the pointer
  28905. * @returns a Sprite or null if no sprite is under the pointer
  28906. */
  28907. Scene.prototype.getPointerOverSprite = function () {
  28908. return this._pointerOverSprite;
  28909. };
  28910. // Physics
  28911. /**
  28912. * Gets the current physics engine
  28913. * @returns a PhysicsEngine or null if none attached
  28914. */
  28915. Scene.prototype.getPhysicsEngine = function () {
  28916. return this._physicsEngine;
  28917. };
  28918. /**
  28919. * Enables physics to the current scene
  28920. * @param gravity defines the scene's gravity for the physics engine
  28921. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28922. * @return a boolean indicating if the physics engine was initialized
  28923. */
  28924. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28925. if (gravity === void 0) { gravity = null; }
  28926. if (this._physicsEngine) {
  28927. return true;
  28928. }
  28929. try {
  28930. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28931. return true;
  28932. }
  28933. catch (e) {
  28934. BABYLON.Tools.Error(e.message);
  28935. return false;
  28936. }
  28937. };
  28938. /**
  28939. * Disables and disposes the physics engine associated with the scene
  28940. */
  28941. Scene.prototype.disablePhysicsEngine = function () {
  28942. if (!this._physicsEngine) {
  28943. return;
  28944. }
  28945. this._physicsEngine.dispose();
  28946. this._physicsEngine = null;
  28947. };
  28948. /**
  28949. * Gets a boolean indicating if there is an active physics engine
  28950. * @returns a boolean indicating if there is an active physics engine
  28951. */
  28952. Scene.prototype.isPhysicsEnabled = function () {
  28953. return this._physicsEngine !== undefined;
  28954. };
  28955. /**
  28956. * Deletes a physics compound impostor
  28957. * @param compound defines the compound to delete
  28958. */
  28959. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28960. var mesh = compound.parts[0].mesh;
  28961. if (mesh.physicsImpostor) {
  28962. mesh.physicsImpostor.dispose( /*true*/);
  28963. mesh.physicsImpostor = null;
  28964. }
  28965. };
  28966. // Misc.
  28967. /** @hidden */
  28968. Scene.prototype._rebuildGeometries = function () {
  28969. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28970. var geometry = _a[_i];
  28971. geometry._rebuild();
  28972. }
  28973. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28974. var mesh = _c[_b];
  28975. mesh._rebuild();
  28976. }
  28977. if (this.postProcessManager) {
  28978. this.postProcessManager._rebuild();
  28979. }
  28980. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28981. var component = _e[_d];
  28982. component.rebuild();
  28983. }
  28984. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28985. var system = _g[_f];
  28986. system.rebuild();
  28987. }
  28988. if (this._postProcessRenderPipelineManager) {
  28989. this._postProcessRenderPipelineManager._rebuild();
  28990. }
  28991. };
  28992. /** @hidden */
  28993. Scene.prototype._rebuildTextures = function () {
  28994. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28995. var texture = _a[_i];
  28996. texture._rebuild();
  28997. }
  28998. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28999. };
  29000. /**
  29001. * Creates a default light for the scene.
  29002. * @param replace Whether to replace the existing lights in the scene.
  29003. */
  29004. Scene.prototype.createDefaultLight = function (replace) {
  29005. if (replace === void 0) { replace = false; }
  29006. // Dispose existing light in replace mode.
  29007. if (replace) {
  29008. if (this.lights) {
  29009. for (var i = 0; i < this.lights.length; i++) {
  29010. this.lights[i].dispose();
  29011. }
  29012. }
  29013. }
  29014. // Light
  29015. if (this.lights.length === 0) {
  29016. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29017. }
  29018. };
  29019. /**
  29020. * Creates a default camera for the scene.
  29021. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29022. * @param replace Whether to replace the existing active camera in the scene.
  29023. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29024. */
  29025. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29026. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29027. if (replace === void 0) { replace = false; }
  29028. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29029. // Dispose existing camera in replace mode.
  29030. if (replace) {
  29031. if (this.activeCamera) {
  29032. this.activeCamera.dispose();
  29033. this.activeCamera = null;
  29034. }
  29035. }
  29036. // Camera
  29037. if (!this.activeCamera) {
  29038. var worldExtends = this.getWorldExtends();
  29039. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29040. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29041. var camera;
  29042. var radius = worldSize.length() * 1.5;
  29043. // empty scene scenario!
  29044. if (!isFinite(radius)) {
  29045. radius = 1;
  29046. worldCenter.copyFromFloats(0, 0, 0);
  29047. }
  29048. if (createArcRotateCamera) {
  29049. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29050. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29051. arcRotateCamera.wheelPrecision = 100 / radius;
  29052. camera = arcRotateCamera;
  29053. }
  29054. else {
  29055. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29056. freeCamera.setTarget(worldCenter);
  29057. camera = freeCamera;
  29058. }
  29059. camera.minZ = radius * 0.01;
  29060. camera.maxZ = radius * 1000;
  29061. camera.speed = radius * 0.2;
  29062. this.activeCamera = camera;
  29063. var canvas = this.getEngine().getRenderingCanvas();
  29064. if (attachCameraControls && canvas) {
  29065. camera.attachControl(canvas);
  29066. }
  29067. }
  29068. };
  29069. /**
  29070. * Creates a default camera and a default light
  29071. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29072. * @param replace defines if the camera and/or light will replace the existing ones
  29073. * @param attachCameraControls defines if attachControl will be called on the new camera
  29074. */
  29075. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29076. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29077. if (replace === void 0) { replace = false; }
  29078. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29079. this.createDefaultLight(replace);
  29080. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29081. };
  29082. /**
  29083. * Creates a new sky box
  29084. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29085. * @param environmentTexture defines the texture to use as environment texture
  29086. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29087. * @param scale defines the overall scale of the skybox
  29088. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29089. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29090. * @returns a new mesh holding the sky box
  29091. */
  29092. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29093. if (pbr === void 0) { pbr = false; }
  29094. if (scale === void 0) { scale = 1000; }
  29095. if (blur === void 0) { blur = 0; }
  29096. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29097. if (!environmentTexture) {
  29098. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29099. return null;
  29100. }
  29101. if (setGlobalEnvTexture) {
  29102. if (environmentTexture) {
  29103. this.environmentTexture = environmentTexture;
  29104. }
  29105. }
  29106. // Skybox
  29107. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29108. if (pbr) {
  29109. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29110. hdrSkyboxMaterial.backFaceCulling = false;
  29111. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29112. if (hdrSkyboxMaterial.reflectionTexture) {
  29113. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29114. }
  29115. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29116. hdrSkyboxMaterial.disableLighting = true;
  29117. hdrSkyboxMaterial.twoSidedLighting = true;
  29118. hdrSkybox.infiniteDistance = true;
  29119. hdrSkybox.material = hdrSkyboxMaterial;
  29120. }
  29121. else {
  29122. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29123. skyboxMaterial.backFaceCulling = false;
  29124. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29125. if (skyboxMaterial.reflectionTexture) {
  29126. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29127. }
  29128. skyboxMaterial.disableLighting = true;
  29129. hdrSkybox.infiniteDistance = true;
  29130. hdrSkybox.material = skyboxMaterial;
  29131. }
  29132. return hdrSkybox;
  29133. };
  29134. /**
  29135. * Creates a new environment
  29136. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29137. * @param options defines the options you can use to configure the environment
  29138. * @returns the new EnvironmentHelper
  29139. */
  29140. Scene.prototype.createDefaultEnvironment = function (options) {
  29141. if (BABYLON.EnvironmentHelper) {
  29142. return new BABYLON.EnvironmentHelper(options, this);
  29143. }
  29144. return null;
  29145. };
  29146. /**
  29147. * Creates a new VREXperienceHelper
  29148. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29149. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29150. * @returns a new VREXperienceHelper
  29151. */
  29152. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29153. if (webVROptions === void 0) { webVROptions = {}; }
  29154. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29155. };
  29156. // Tags
  29157. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29158. if (tagsQuery === undefined) {
  29159. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29160. return list;
  29161. }
  29162. var listByTags = [];
  29163. forEach = forEach || (function (item) { return; });
  29164. for (var i in list) {
  29165. var item = list[i];
  29166. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29167. listByTags.push(item);
  29168. forEach(item);
  29169. }
  29170. }
  29171. return listByTags;
  29172. };
  29173. /**
  29174. * Get a list of meshes by tags
  29175. * @param tagsQuery defines the tags query to use
  29176. * @param forEach defines a predicate used to filter results
  29177. * @returns an array of Mesh
  29178. */
  29179. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29180. return this._getByTags(this.meshes, tagsQuery, forEach);
  29181. };
  29182. /**
  29183. * Get a list of cameras by tags
  29184. * @param tagsQuery defines the tags query to use
  29185. * @param forEach defines a predicate used to filter results
  29186. * @returns an array of Camera
  29187. */
  29188. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29189. return this._getByTags(this.cameras, tagsQuery, forEach);
  29190. };
  29191. /**
  29192. * Get a list of lights by tags
  29193. * @param tagsQuery defines the tags query to use
  29194. * @param forEach defines a predicate used to filter results
  29195. * @returns an array of Light
  29196. */
  29197. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29198. return this._getByTags(this.lights, tagsQuery, forEach);
  29199. };
  29200. /**
  29201. * Get a list of materials by tags
  29202. * @param tagsQuery defines the tags query to use
  29203. * @param forEach defines a predicate used to filter results
  29204. * @returns an array of Material
  29205. */
  29206. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29207. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29208. };
  29209. /**
  29210. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29211. * This allowed control for front to back rendering or reversly depending of the special needs.
  29212. *
  29213. * @param renderingGroupId The rendering group id corresponding to its index
  29214. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29215. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29216. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29217. */
  29218. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29219. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29220. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29221. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29222. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29223. };
  29224. /**
  29225. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29226. *
  29227. * @param renderingGroupId The rendering group id corresponding to its index
  29228. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29229. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29230. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29231. */
  29232. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29233. if (depth === void 0) { depth = true; }
  29234. if (stencil === void 0) { stencil = true; }
  29235. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29236. };
  29237. /**
  29238. * Will flag all materials as dirty to trigger new shader compilation
  29239. * @param flag defines the flag used to specify which material part must be marked as dirty
  29240. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29241. */
  29242. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29243. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29244. var material = _a[_i];
  29245. if (predicate && !predicate(material)) {
  29246. continue;
  29247. }
  29248. material.markAsDirty(flag);
  29249. }
  29250. };
  29251. /** @hidden */
  29252. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29253. var _this = this;
  29254. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29255. this._activeRequests.push(request);
  29256. request.onCompleteObservable.add(function (request) {
  29257. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29258. });
  29259. return request;
  29260. };
  29261. /** @hidden */
  29262. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29263. var _this = this;
  29264. return new Promise(function (resolve, reject) {
  29265. _this._loadFile(url, function (data) {
  29266. resolve(data);
  29267. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29268. reject(exception);
  29269. });
  29270. });
  29271. };
  29272. // Statics
  29273. Scene._FOGMODE_NONE = 0;
  29274. Scene._FOGMODE_EXP = 1;
  29275. Scene._FOGMODE_EXP2 = 2;
  29276. Scene._FOGMODE_LINEAR = 3;
  29277. Scene._uniqueIdCounter = 0;
  29278. /**
  29279. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29280. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29281. */
  29282. Scene.MinDeltaTime = 1.0;
  29283. /**
  29284. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29285. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29286. */
  29287. Scene.MaxDeltaTime = 1000.0;
  29288. /** The distance in pixel that you have to move to prevent some events */
  29289. Scene.DragMovementThreshold = 10; // in pixels
  29290. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29291. Scene.LongPressDelay = 500; // in milliseconds
  29292. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29293. Scene.DoubleClickDelay = 300; // in milliseconds
  29294. /** If you need to check double click without raising a single click at first click, enable this flag */
  29295. Scene.ExclusiveDoubleClickMode = false;
  29296. return Scene;
  29297. }(BABYLON.AbstractScene));
  29298. BABYLON.Scene = Scene;
  29299. })(BABYLON || (BABYLON = {}));
  29300. //# sourceMappingURL=babylon.scene.js.map
  29301. var BABYLON;
  29302. (function (BABYLON) {
  29303. /**
  29304. * Set of assets to keep when moving a scene into an asset container.
  29305. */
  29306. var KeepAssets = /** @class */ (function (_super) {
  29307. __extends(KeepAssets, _super);
  29308. function KeepAssets() {
  29309. return _super !== null && _super.apply(this, arguments) || this;
  29310. }
  29311. return KeepAssets;
  29312. }(BABYLON.AbstractScene));
  29313. BABYLON.KeepAssets = KeepAssets;
  29314. /**
  29315. * Container with a set of assets that can be added or removed from a scene.
  29316. */
  29317. var AssetContainer = /** @class */ (function (_super) {
  29318. __extends(AssetContainer, _super);
  29319. /**
  29320. * Instantiates an AssetContainer.
  29321. * @param scene The scene the AssetContainer belongs to.
  29322. */
  29323. function AssetContainer(scene) {
  29324. var _this = _super.call(this) || this;
  29325. _this.scene = scene;
  29326. return _this;
  29327. }
  29328. /**
  29329. * Adds all the assets from the container to the scene.
  29330. */
  29331. AssetContainer.prototype.addAllToScene = function () {
  29332. var _this = this;
  29333. this.cameras.forEach(function (o) {
  29334. _this.scene.addCamera(o);
  29335. });
  29336. this.lights.forEach(function (o) {
  29337. _this.scene.addLight(o);
  29338. });
  29339. this.meshes.forEach(function (o) {
  29340. _this.scene.addMesh(o);
  29341. });
  29342. this.skeletons.forEach(function (o) {
  29343. _this.scene.addSkeleton(o);
  29344. });
  29345. this.animations.forEach(function (o) {
  29346. _this.scene.addAnimation(o);
  29347. });
  29348. this.animationGroups.forEach(function (o) {
  29349. _this.scene.addAnimationGroup(o);
  29350. });
  29351. this.multiMaterials.forEach(function (o) {
  29352. _this.scene.addMultiMaterial(o);
  29353. });
  29354. this.materials.forEach(function (o) {
  29355. _this.scene.addMaterial(o);
  29356. });
  29357. this.morphTargetManagers.forEach(function (o) {
  29358. _this.scene.addMorphTargetManager(o);
  29359. });
  29360. this.geometries.forEach(function (o) {
  29361. _this.scene.addGeometry(o);
  29362. });
  29363. this.transformNodes.forEach(function (o) {
  29364. _this.scene.addTransformNode(o);
  29365. });
  29366. this.actionManagers.forEach(function (o) {
  29367. _this.scene.addActionManager(o);
  29368. });
  29369. this.sounds.forEach(function (o) {
  29370. o.play();
  29371. o.autoplay = true;
  29372. _this.scene.mainSoundTrack.AddSound(o);
  29373. });
  29374. this.textures.forEach(function (o) {
  29375. _this.scene.addTexture(o);
  29376. });
  29377. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29378. var component = _a[_i];
  29379. component.addFromContainer(this.scene);
  29380. }
  29381. };
  29382. /**
  29383. * Removes all the assets in the container from the scene
  29384. */
  29385. AssetContainer.prototype.removeAllFromScene = function () {
  29386. var _this = this;
  29387. this.cameras.forEach(function (o) {
  29388. _this.scene.removeCamera(o);
  29389. });
  29390. this.lights.forEach(function (o) {
  29391. _this.scene.removeLight(o);
  29392. });
  29393. this.meshes.forEach(function (o) {
  29394. _this.scene.removeMesh(o);
  29395. });
  29396. this.skeletons.forEach(function (o) {
  29397. _this.scene.removeSkeleton(o);
  29398. });
  29399. this.animations.forEach(function (o) {
  29400. _this.scene.removeAnimation(o);
  29401. });
  29402. this.animationGroups.forEach(function (o) {
  29403. _this.scene.removeAnimationGroup(o);
  29404. });
  29405. this.multiMaterials.forEach(function (o) {
  29406. _this.scene.removeMultiMaterial(o);
  29407. });
  29408. this.materials.forEach(function (o) {
  29409. _this.scene.removeMaterial(o);
  29410. });
  29411. this.morphTargetManagers.forEach(function (o) {
  29412. _this.scene.removeMorphTargetManager(o);
  29413. });
  29414. this.geometries.forEach(function (o) {
  29415. _this.scene.removeGeometry(o);
  29416. });
  29417. this.transformNodes.forEach(function (o) {
  29418. _this.scene.removeTransformNode(o);
  29419. });
  29420. this.actionManagers.forEach(function (o) {
  29421. _this.scene.removeActionManager(o);
  29422. });
  29423. this.sounds.forEach(function (o) {
  29424. o.stop();
  29425. o.autoplay = false;
  29426. _this.scene.mainSoundTrack.RemoveSound(o);
  29427. });
  29428. this.textures.forEach(function (o) {
  29429. _this.scene.removeTexture(o);
  29430. });
  29431. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29432. var component = _a[_i];
  29433. component.removeFromContainer(this.scene);
  29434. }
  29435. };
  29436. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29437. if (!sourceAssets) {
  29438. return;
  29439. }
  29440. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29441. var asset = sourceAssets_1[_i];
  29442. var move = true;
  29443. if (keepAssets) {
  29444. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29445. var keepAsset = keepAssets_1[_a];
  29446. if (asset === keepAsset) {
  29447. move = false;
  29448. break;
  29449. }
  29450. }
  29451. }
  29452. if (move) {
  29453. targetAssets.push(asset);
  29454. }
  29455. }
  29456. };
  29457. /**
  29458. * Removes all the assets contained in the scene and adds them to the container.
  29459. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29460. */
  29461. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29462. if (keepAssets === undefined) {
  29463. keepAssets = new KeepAssets();
  29464. }
  29465. for (var key in this) {
  29466. if (this.hasOwnProperty(key)) {
  29467. this[key] = this[key] || [];
  29468. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29469. }
  29470. }
  29471. this.removeAllFromScene();
  29472. };
  29473. /**
  29474. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29475. * @returns the root mesh
  29476. */
  29477. AssetContainer.prototype.createRootMesh = function () {
  29478. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29479. this.meshes.forEach(function (m) {
  29480. if (!m.parent) {
  29481. rootMesh.addChild(m);
  29482. }
  29483. });
  29484. this.meshes.unshift(rootMesh);
  29485. return rootMesh;
  29486. };
  29487. return AssetContainer;
  29488. }(BABYLON.AbstractScene));
  29489. BABYLON.AssetContainer = AssetContainer;
  29490. })(BABYLON || (BABYLON = {}));
  29491. //# sourceMappingURL=babylon.assetContainer.js.map
  29492. var BABYLON;
  29493. (function (BABYLON) {
  29494. var Buffer = /** @class */ (function () {
  29495. /**
  29496. * Constructor
  29497. * @param engine the engine
  29498. * @param data the data to use for this buffer
  29499. * @param updatable whether the data is updatable
  29500. * @param stride the stride (optional)
  29501. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29502. * @param instanced whether the buffer is instanced (optional)
  29503. * @param useBytes set to true if the stride in in bytes (optional)
  29504. */
  29505. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29506. if (stride === void 0) { stride = 0; }
  29507. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29508. if (instanced === void 0) { instanced = false; }
  29509. if (useBytes === void 0) { useBytes = false; }
  29510. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29511. this._engine = engine.getScene().getEngine();
  29512. }
  29513. else {
  29514. this._engine = engine;
  29515. }
  29516. this._updatable = updatable;
  29517. this._instanced = instanced;
  29518. this._data = data;
  29519. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29520. if (!postponeInternalCreation) { // by default
  29521. this.create();
  29522. }
  29523. }
  29524. /**
  29525. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29526. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29527. * @param offset defines offset in the buffer (0 by default)
  29528. * @param size defines the size in floats of attributes (position is 3 for instance)
  29529. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29530. * @param instanced defines if the vertex buffer contains indexed data
  29531. * @param useBytes defines if the offset and stride are in bytes
  29532. * @returns the new vertex buffer
  29533. */
  29534. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29535. if (useBytes === void 0) { useBytes = false; }
  29536. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29537. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29538. // a lot of these parameters are ignored as they are overriden by the buffer
  29539. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29540. };
  29541. // Properties
  29542. Buffer.prototype.isUpdatable = function () {
  29543. return this._updatable;
  29544. };
  29545. Buffer.prototype.getData = function () {
  29546. return this._data;
  29547. };
  29548. Buffer.prototype.getBuffer = function () {
  29549. return this._buffer;
  29550. };
  29551. /**
  29552. * Gets the stride in float32 units (i.e. byte stride / 4).
  29553. * May not be an integer if the byte stride is not divisible by 4.
  29554. * DEPRECATED. Use byteStride instead.
  29555. * @returns the stride in float32 units
  29556. */
  29557. Buffer.prototype.getStrideSize = function () {
  29558. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29559. };
  29560. // Methods
  29561. Buffer.prototype.create = function (data) {
  29562. if (data === void 0) { data = null; }
  29563. if (!data && this._buffer) {
  29564. return; // nothing to do
  29565. }
  29566. data = data || this._data;
  29567. if (!data) {
  29568. return;
  29569. }
  29570. if (!this._buffer) { // create buffer
  29571. if (this._updatable) {
  29572. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29573. this._data = data;
  29574. }
  29575. else {
  29576. this._buffer = this._engine.createVertexBuffer(data);
  29577. }
  29578. }
  29579. else if (this._updatable) { // update buffer
  29580. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29581. this._data = data;
  29582. }
  29583. };
  29584. Buffer.prototype._rebuild = function () {
  29585. this._buffer = null;
  29586. this.create(this._data);
  29587. };
  29588. Buffer.prototype.update = function (data) {
  29589. this.create(data);
  29590. };
  29591. /**
  29592. * Updates the data directly.
  29593. * @param data the new data
  29594. * @param offset the new offset
  29595. * @param vertexCount the vertex count (optional)
  29596. * @param useBytes set to true if the offset is in bytes
  29597. */
  29598. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29599. if (useBytes === void 0) { useBytes = false; }
  29600. if (!this._buffer) {
  29601. return;
  29602. }
  29603. if (this._updatable) { // update buffer
  29604. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29605. this._data = null;
  29606. }
  29607. };
  29608. Buffer.prototype.dispose = function () {
  29609. if (!this._buffer) {
  29610. return;
  29611. }
  29612. if (this._engine._releaseBuffer(this._buffer)) {
  29613. this._buffer = null;
  29614. }
  29615. };
  29616. return Buffer;
  29617. }());
  29618. BABYLON.Buffer = Buffer;
  29619. })(BABYLON || (BABYLON = {}));
  29620. //# sourceMappingURL=babylon.buffer.js.map
  29621. var BABYLON;
  29622. (function (BABYLON) {
  29623. var VertexBuffer = /** @class */ (function () {
  29624. /**
  29625. * Constructor
  29626. * @param engine the engine
  29627. * @param data the data to use for this vertex buffer
  29628. * @param kind the vertex buffer kind
  29629. * @param updatable whether the data is updatable
  29630. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29631. * @param stride the stride (optional)
  29632. * @param instanced whether the buffer is instanced (optional)
  29633. * @param offset the offset of the data (optional)
  29634. * @param size the number of components (optional)
  29635. * @param type the type of the component (optional)
  29636. * @param normalized whether the data contains normalized data (optional)
  29637. * @param useBytes set to true if stride and offset are in bytes (optional)
  29638. */
  29639. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29640. if (normalized === void 0) { normalized = false; }
  29641. if (useBytes === void 0) { useBytes = false; }
  29642. if (data instanceof BABYLON.Buffer) {
  29643. this._buffer = data;
  29644. this._ownsBuffer = false;
  29645. }
  29646. else {
  29647. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29648. this._ownsBuffer = true;
  29649. }
  29650. this._kind = kind;
  29651. if (type == undefined) {
  29652. var data_1 = this.getData();
  29653. this.type = VertexBuffer.FLOAT;
  29654. if (data_1 instanceof Int8Array)
  29655. this.type = VertexBuffer.BYTE;
  29656. else if (data_1 instanceof Uint8Array)
  29657. this.type = VertexBuffer.UNSIGNED_BYTE;
  29658. else if (data_1 instanceof Int16Array)
  29659. this.type = VertexBuffer.SHORT;
  29660. else if (data_1 instanceof Uint16Array)
  29661. this.type = VertexBuffer.UNSIGNED_SHORT;
  29662. else if (data_1 instanceof Int32Array)
  29663. this.type = VertexBuffer.INT;
  29664. else if (data_1 instanceof Uint32Array)
  29665. this.type = VertexBuffer.UNSIGNED_INT;
  29666. }
  29667. else {
  29668. this.type = type;
  29669. }
  29670. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29671. if (useBytes) {
  29672. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29673. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29674. this.byteOffset = offset || 0;
  29675. }
  29676. else {
  29677. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29678. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29679. this.byteOffset = (offset || 0) * typeByteLength;
  29680. }
  29681. this.normalized = normalized;
  29682. this._instanced = instanced !== undefined ? instanced : false;
  29683. this._instanceDivisor = instanced ? 1 : 0;
  29684. }
  29685. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29686. /**
  29687. * Gets or sets the instance divisor when in instanced mode
  29688. */
  29689. get: function () {
  29690. return this._instanceDivisor;
  29691. },
  29692. set: function (value) {
  29693. this._instanceDivisor = value;
  29694. if (value == 0) {
  29695. this._instanced = false;
  29696. }
  29697. else {
  29698. this._instanced = true;
  29699. }
  29700. },
  29701. enumerable: true,
  29702. configurable: true
  29703. });
  29704. VertexBuffer.prototype._rebuild = function () {
  29705. if (!this._buffer) {
  29706. return;
  29707. }
  29708. this._buffer._rebuild();
  29709. };
  29710. /**
  29711. * Returns the kind of the VertexBuffer (string).
  29712. */
  29713. VertexBuffer.prototype.getKind = function () {
  29714. return this._kind;
  29715. };
  29716. // Properties
  29717. /**
  29718. * Boolean : is the VertexBuffer updatable ?
  29719. */
  29720. VertexBuffer.prototype.isUpdatable = function () {
  29721. return this._buffer.isUpdatable();
  29722. };
  29723. /**
  29724. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29725. */
  29726. VertexBuffer.prototype.getData = function () {
  29727. return this._buffer.getData();
  29728. };
  29729. /**
  29730. * Returns the WebGLBuffer associated to the VertexBuffer.
  29731. */
  29732. VertexBuffer.prototype.getBuffer = function () {
  29733. return this._buffer.getBuffer();
  29734. };
  29735. /**
  29736. * Returns the stride as a multiple of the type byte length.
  29737. * DEPRECATED. Use byteStride instead.
  29738. */
  29739. VertexBuffer.prototype.getStrideSize = function () {
  29740. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29741. };
  29742. /**
  29743. * Returns the offset as a multiple of the type byte length.
  29744. * DEPRECATED. Use byteOffset instead.
  29745. */
  29746. VertexBuffer.prototype.getOffset = function () {
  29747. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29748. };
  29749. /**
  29750. * Returns the number of components per vertex attribute (integer).
  29751. */
  29752. VertexBuffer.prototype.getSize = function () {
  29753. return this._size;
  29754. };
  29755. /**
  29756. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29757. */
  29758. VertexBuffer.prototype.getIsInstanced = function () {
  29759. return this._instanced;
  29760. };
  29761. /**
  29762. * Returns the instancing divisor, zero for non-instanced (integer).
  29763. */
  29764. VertexBuffer.prototype.getInstanceDivisor = function () {
  29765. return this._instanceDivisor;
  29766. };
  29767. // Methods
  29768. /**
  29769. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29770. * Returns the created WebGLBuffer.
  29771. */
  29772. VertexBuffer.prototype.create = function (data) {
  29773. return this._buffer.create(data);
  29774. };
  29775. /**
  29776. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29777. * This function will create a new buffer if the current one is not updatable
  29778. * Returns the updated WebGLBuffer.
  29779. */
  29780. VertexBuffer.prototype.update = function (data) {
  29781. return this._buffer.update(data);
  29782. };
  29783. /**
  29784. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29785. * Returns the directly updated WebGLBuffer.
  29786. * @param data the new data
  29787. * @param offset the new offset
  29788. * @param useBytes set to true if the offset is in bytes
  29789. */
  29790. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29791. if (useBytes === void 0) { useBytes = false; }
  29792. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29793. };
  29794. /**
  29795. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29796. */
  29797. VertexBuffer.prototype.dispose = function () {
  29798. if (this._ownsBuffer) {
  29799. this._buffer.dispose();
  29800. }
  29801. };
  29802. /**
  29803. * Enumerates each value of this vertex buffer as numbers.
  29804. * @param count the number of values to enumerate
  29805. * @param callback the callback function called for each value
  29806. */
  29807. VertexBuffer.prototype.forEach = function (count, callback) {
  29808. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29809. };
  29810. Object.defineProperty(VertexBuffer, "PositionKind", {
  29811. get: function () {
  29812. return VertexBuffer._PositionKind;
  29813. },
  29814. enumerable: true,
  29815. configurable: true
  29816. });
  29817. Object.defineProperty(VertexBuffer, "NormalKind", {
  29818. get: function () {
  29819. return VertexBuffer._NormalKind;
  29820. },
  29821. enumerable: true,
  29822. configurable: true
  29823. });
  29824. Object.defineProperty(VertexBuffer, "TangentKind", {
  29825. get: function () {
  29826. return VertexBuffer._TangentKind;
  29827. },
  29828. enumerable: true,
  29829. configurable: true
  29830. });
  29831. Object.defineProperty(VertexBuffer, "UVKind", {
  29832. get: function () {
  29833. return VertexBuffer._UVKind;
  29834. },
  29835. enumerable: true,
  29836. configurable: true
  29837. });
  29838. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29839. get: function () {
  29840. return VertexBuffer._UV2Kind;
  29841. },
  29842. enumerable: true,
  29843. configurable: true
  29844. });
  29845. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29846. get: function () {
  29847. return VertexBuffer._UV3Kind;
  29848. },
  29849. enumerable: true,
  29850. configurable: true
  29851. });
  29852. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29853. get: function () {
  29854. return VertexBuffer._UV4Kind;
  29855. },
  29856. enumerable: true,
  29857. configurable: true
  29858. });
  29859. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29860. get: function () {
  29861. return VertexBuffer._UV5Kind;
  29862. },
  29863. enumerable: true,
  29864. configurable: true
  29865. });
  29866. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29867. get: function () {
  29868. return VertexBuffer._UV6Kind;
  29869. },
  29870. enumerable: true,
  29871. configurable: true
  29872. });
  29873. Object.defineProperty(VertexBuffer, "ColorKind", {
  29874. get: function () {
  29875. return VertexBuffer._ColorKind;
  29876. },
  29877. enumerable: true,
  29878. configurable: true
  29879. });
  29880. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29881. get: function () {
  29882. return VertexBuffer._MatricesIndicesKind;
  29883. },
  29884. enumerable: true,
  29885. configurable: true
  29886. });
  29887. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29888. get: function () {
  29889. return VertexBuffer._MatricesWeightsKind;
  29890. },
  29891. enumerable: true,
  29892. configurable: true
  29893. });
  29894. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29895. get: function () {
  29896. return VertexBuffer._MatricesIndicesExtraKind;
  29897. },
  29898. enumerable: true,
  29899. configurable: true
  29900. });
  29901. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29902. get: function () {
  29903. return VertexBuffer._MatricesWeightsExtraKind;
  29904. },
  29905. enumerable: true,
  29906. configurable: true
  29907. });
  29908. /**
  29909. * Deduces the stride given a kind.
  29910. * @param kind The kind string to deduce
  29911. * @returns The deduced stride
  29912. */
  29913. VertexBuffer.DeduceStride = function (kind) {
  29914. switch (kind) {
  29915. case VertexBuffer.UVKind:
  29916. case VertexBuffer.UV2Kind:
  29917. case VertexBuffer.UV3Kind:
  29918. case VertexBuffer.UV4Kind:
  29919. case VertexBuffer.UV5Kind:
  29920. case VertexBuffer.UV6Kind:
  29921. return 2;
  29922. case VertexBuffer.NormalKind:
  29923. case VertexBuffer.PositionKind:
  29924. return 3;
  29925. case VertexBuffer.ColorKind:
  29926. case VertexBuffer.MatricesIndicesKind:
  29927. case VertexBuffer.MatricesIndicesExtraKind:
  29928. case VertexBuffer.MatricesWeightsKind:
  29929. case VertexBuffer.MatricesWeightsExtraKind:
  29930. case VertexBuffer.TangentKind:
  29931. return 4;
  29932. default:
  29933. throw new Error("Invalid kind '" + kind + "'");
  29934. }
  29935. };
  29936. /**
  29937. * Gets the byte length of the given type.
  29938. * @param type the type
  29939. * @returns the number of bytes
  29940. */
  29941. VertexBuffer.GetTypeByteLength = function (type) {
  29942. switch (type) {
  29943. case VertexBuffer.BYTE:
  29944. case VertexBuffer.UNSIGNED_BYTE:
  29945. return 1;
  29946. case VertexBuffer.SHORT:
  29947. case VertexBuffer.UNSIGNED_SHORT:
  29948. return 2;
  29949. case VertexBuffer.INT:
  29950. case VertexBuffer.FLOAT:
  29951. return 4;
  29952. default:
  29953. throw new Error("Invalid type '" + type + "'");
  29954. }
  29955. };
  29956. /**
  29957. * Enumerates each value of the given parameters as numbers.
  29958. * @param data the data to enumerate
  29959. * @param byteOffset the byte offset of the data
  29960. * @param byteStride the byte stride of the data
  29961. * @param componentCount the number of components per element
  29962. * @param componentType the type of the component
  29963. * @param count the total number of components
  29964. * @param normalized whether the data is normalized
  29965. * @param callback the callback function called for each value
  29966. */
  29967. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29968. if (data instanceof Array) {
  29969. var offset = byteOffset / 4;
  29970. var stride = byteStride / 4;
  29971. for (var index = 0; index < count; index += componentCount) {
  29972. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29973. callback(data[offset + componentIndex], index + componentIndex);
  29974. }
  29975. offset += stride;
  29976. }
  29977. }
  29978. else {
  29979. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29980. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29981. for (var index = 0; index < count; index += componentCount) {
  29982. var componentByteOffset = byteOffset;
  29983. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29984. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29985. callback(value, index + componentIndex);
  29986. componentByteOffset += componentByteLength;
  29987. }
  29988. byteOffset += byteStride;
  29989. }
  29990. }
  29991. };
  29992. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29993. switch (type) {
  29994. case VertexBuffer.BYTE: {
  29995. var value = dataView.getInt8(byteOffset);
  29996. if (normalized) {
  29997. value = Math.max(value / 127, -1);
  29998. }
  29999. return value;
  30000. }
  30001. case VertexBuffer.UNSIGNED_BYTE: {
  30002. var value = dataView.getUint8(byteOffset);
  30003. if (normalized) {
  30004. value = value / 255;
  30005. }
  30006. return value;
  30007. }
  30008. case VertexBuffer.SHORT: {
  30009. var value = dataView.getInt16(byteOffset, true);
  30010. if (normalized) {
  30011. value = Math.max(value / 16383, -1);
  30012. }
  30013. return value;
  30014. }
  30015. case VertexBuffer.UNSIGNED_SHORT: {
  30016. var value = dataView.getUint16(byteOffset, true);
  30017. if (normalized) {
  30018. value = value / 65535;
  30019. }
  30020. return value;
  30021. }
  30022. case VertexBuffer.FLOAT: {
  30023. return dataView.getFloat32(byteOffset, true);
  30024. }
  30025. default: {
  30026. throw new Error("Invalid component type " + type);
  30027. }
  30028. }
  30029. };
  30030. /**
  30031. * The byte type.
  30032. */
  30033. VertexBuffer.BYTE = 5120;
  30034. /**
  30035. * The unsigned byte type.
  30036. */
  30037. VertexBuffer.UNSIGNED_BYTE = 5121;
  30038. /**
  30039. * The short type.
  30040. */
  30041. VertexBuffer.SHORT = 5122;
  30042. /**
  30043. * The unsigned short type.
  30044. */
  30045. VertexBuffer.UNSIGNED_SHORT = 5123;
  30046. /**
  30047. * The integer type.
  30048. */
  30049. VertexBuffer.INT = 5124;
  30050. /**
  30051. * The unsigned integer type.
  30052. */
  30053. VertexBuffer.UNSIGNED_INT = 5125;
  30054. /**
  30055. * The float type.
  30056. */
  30057. VertexBuffer.FLOAT = 5126;
  30058. // Enums
  30059. VertexBuffer._PositionKind = "position";
  30060. VertexBuffer._NormalKind = "normal";
  30061. VertexBuffer._TangentKind = "tangent";
  30062. VertexBuffer._UVKind = "uv";
  30063. VertexBuffer._UV2Kind = "uv2";
  30064. VertexBuffer._UV3Kind = "uv3";
  30065. VertexBuffer._UV4Kind = "uv4";
  30066. VertexBuffer._UV5Kind = "uv5";
  30067. VertexBuffer._UV6Kind = "uv6";
  30068. VertexBuffer._ColorKind = "color";
  30069. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30070. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30071. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30072. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30073. return VertexBuffer;
  30074. }());
  30075. BABYLON.VertexBuffer = VertexBuffer;
  30076. })(BABYLON || (BABYLON = {}));
  30077. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30078. var BABYLON;
  30079. (function (BABYLON) {
  30080. /**
  30081. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30082. */
  30083. var DummyInternalTextureTracker = /** @class */ (function () {
  30084. function DummyInternalTextureTracker() {
  30085. /**
  30086. * Gets or set the previous tracker in the list
  30087. */
  30088. this.previous = null;
  30089. /**
  30090. * Gets or set the next tracker in the list
  30091. */
  30092. this.next = null;
  30093. }
  30094. return DummyInternalTextureTracker;
  30095. }());
  30096. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30097. })(BABYLON || (BABYLON = {}));
  30098. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30099. var BABYLON;
  30100. (function (BABYLON) {
  30101. /**
  30102. * Class used to store data associated with WebGL texture data for the engine
  30103. * This class should not be used directly
  30104. */
  30105. var InternalTexture = /** @class */ (function () {
  30106. /**
  30107. * Creates a new InternalTexture
  30108. * @param engine defines the engine to use
  30109. * @param dataSource defines the type of data that will be used
  30110. */
  30111. function InternalTexture(engine, dataSource) {
  30112. /**
  30113. * Observable called when the texture is loaded
  30114. */
  30115. this.onLoadedObservable = new BABYLON.Observable();
  30116. /**
  30117. * Gets or set the previous tracker in the list
  30118. */
  30119. this.previous = null;
  30120. /**
  30121. * Gets or set the next tracker in the list
  30122. */
  30123. this.next = null;
  30124. // Private
  30125. /** @hidden */
  30126. this._initialSlot = -1;
  30127. /** @hidden */
  30128. this._designatedSlot = -1;
  30129. /** @hidden */
  30130. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30131. /** @hidden */
  30132. this._comparisonFunction = 0;
  30133. /** @hidden */
  30134. this._sphericalPolynomial = null;
  30135. /** @hidden */
  30136. this._lodGenerationScale = 0;
  30137. /** @hidden */
  30138. this._lodGenerationOffset = 0;
  30139. /** @hidden */
  30140. this._isRGBD = false;
  30141. /** @hidden */
  30142. this._references = 1;
  30143. this._engine = engine;
  30144. this._dataSource = dataSource;
  30145. this._webGLTexture = engine._createTexture();
  30146. }
  30147. /**
  30148. * Gets the Engine the texture belongs to.
  30149. * @returns The babylon engine
  30150. */
  30151. InternalTexture.prototype.getEngine = function () {
  30152. return this._engine;
  30153. };
  30154. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30155. /**
  30156. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30157. */
  30158. get: function () {
  30159. return this._dataSource;
  30160. },
  30161. enumerable: true,
  30162. configurable: true
  30163. });
  30164. /**
  30165. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30166. */
  30167. InternalTexture.prototype.incrementReferences = function () {
  30168. this._references++;
  30169. };
  30170. /**
  30171. * Change the size of the texture (not the size of the content)
  30172. * @param width defines the new width
  30173. * @param height defines the new height
  30174. * @param depth defines the new depth (1 by default)
  30175. */
  30176. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30177. if (depth === void 0) { depth = 1; }
  30178. this.width = width;
  30179. this.height = height;
  30180. this.depth = depth;
  30181. this.baseWidth = width;
  30182. this.baseHeight = height;
  30183. this.baseDepth = depth;
  30184. this._size = width * height * depth;
  30185. };
  30186. /** @hidden */
  30187. InternalTexture.prototype._rebuild = function () {
  30188. var _this = this;
  30189. var proxy;
  30190. this.isReady = false;
  30191. this._cachedCoordinatesMode = null;
  30192. this._cachedWrapU = null;
  30193. this._cachedWrapV = null;
  30194. this._cachedAnisotropicFilteringLevel = null;
  30195. switch (this._dataSource) {
  30196. case InternalTexture.DATASOURCE_TEMP:
  30197. return;
  30198. case InternalTexture.DATASOURCE_URL:
  30199. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30200. _this.isReady = true;
  30201. }, null, this._buffer, undefined, this.format);
  30202. proxy._swapAndDie(this);
  30203. return;
  30204. case InternalTexture.DATASOURCE_RAW:
  30205. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30206. proxy._swapAndDie(this);
  30207. this.isReady = true;
  30208. return;
  30209. case InternalTexture.DATASOURCE_RAW3D:
  30210. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30211. proxy._swapAndDie(this);
  30212. this.isReady = true;
  30213. return;
  30214. case InternalTexture.DATASOURCE_DYNAMIC:
  30215. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30216. proxy._swapAndDie(this);
  30217. // The engine will make sure to update content so no need to flag it as isReady = true
  30218. return;
  30219. case InternalTexture.DATASOURCE_RENDERTARGET:
  30220. var options = new BABYLON.RenderTargetCreationOptions();
  30221. options.generateDepthBuffer = this._generateDepthBuffer;
  30222. options.generateMipMaps = this.generateMipMaps;
  30223. options.generateStencilBuffer = this._generateStencilBuffer;
  30224. options.samplingMode = this.samplingMode;
  30225. options.type = this.type;
  30226. if (this.isCube) {
  30227. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30228. }
  30229. else {
  30230. var size = {
  30231. width: this.width,
  30232. height: this.height
  30233. };
  30234. proxy = this._engine.createRenderTargetTexture(size, options);
  30235. }
  30236. proxy._swapAndDie(this);
  30237. this.isReady = true;
  30238. return;
  30239. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30240. var depthTextureOptions = {
  30241. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30242. comparisonFunction: this._comparisonFunction,
  30243. generateStencil: this._generateStencilBuffer,
  30244. isCube: this.isCube
  30245. };
  30246. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30247. proxy._swapAndDie(this);
  30248. this.isReady = true;
  30249. return;
  30250. case InternalTexture.DATASOURCE_CUBE:
  30251. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30252. _this.isReady = true;
  30253. }, null, this.format, this._extension);
  30254. proxy._swapAndDie(this);
  30255. return;
  30256. case InternalTexture.DATASOURCE_CUBERAW:
  30257. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30258. proxy._swapAndDie(this);
  30259. this.isReady = true;
  30260. return;
  30261. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30262. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30263. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30264. _this.isReady = true;
  30265. });
  30266. proxy._swapAndDie(this);
  30267. return;
  30268. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30269. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30270. if (proxy) {
  30271. proxy._swapAndDie(_this);
  30272. }
  30273. _this.isReady = true;
  30274. }, null, this.format, this._extension);
  30275. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30276. return;
  30277. }
  30278. };
  30279. InternalTexture.prototype._swapAndDie = function (target) {
  30280. target._webGLTexture = this._webGLTexture;
  30281. if (this._framebuffer) {
  30282. target._framebuffer = this._framebuffer;
  30283. }
  30284. if (this._depthStencilBuffer) {
  30285. target._depthStencilBuffer = this._depthStencilBuffer;
  30286. }
  30287. if (this._lodTextureHigh) {
  30288. if (target._lodTextureHigh) {
  30289. target._lodTextureHigh.dispose();
  30290. }
  30291. target._lodTextureHigh = this._lodTextureHigh;
  30292. }
  30293. if (this._lodTextureMid) {
  30294. if (target._lodTextureMid) {
  30295. target._lodTextureMid.dispose();
  30296. }
  30297. target._lodTextureMid = this._lodTextureMid;
  30298. }
  30299. if (this._lodTextureLow) {
  30300. if (target._lodTextureLow) {
  30301. target._lodTextureLow.dispose();
  30302. }
  30303. target._lodTextureLow = this._lodTextureLow;
  30304. }
  30305. var cache = this._engine.getLoadedTexturesCache();
  30306. var index = cache.indexOf(this);
  30307. if (index !== -1) {
  30308. cache.splice(index, 1);
  30309. }
  30310. };
  30311. /**
  30312. * Dispose the current allocated resources
  30313. */
  30314. InternalTexture.prototype.dispose = function () {
  30315. if (!this._webGLTexture) {
  30316. return;
  30317. }
  30318. this._references--;
  30319. if (this._references === 0) {
  30320. this._engine._releaseTexture(this);
  30321. this._webGLTexture = null;
  30322. this.previous = null;
  30323. this.next = null;
  30324. }
  30325. };
  30326. /**
  30327. * The source of the texture data is unknown
  30328. */
  30329. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30330. /**
  30331. * Texture data comes from an URL
  30332. */
  30333. InternalTexture.DATASOURCE_URL = 1;
  30334. /**
  30335. * Texture data is only used for temporary storage
  30336. */
  30337. InternalTexture.DATASOURCE_TEMP = 2;
  30338. /**
  30339. * Texture data comes from raw data (ArrayBuffer)
  30340. */
  30341. InternalTexture.DATASOURCE_RAW = 3;
  30342. /**
  30343. * Texture content is dynamic (video or dynamic texture)
  30344. */
  30345. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30346. /**
  30347. * Texture content is generated by rendering to it
  30348. */
  30349. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30350. /**
  30351. * Texture content is part of a multi render target process
  30352. */
  30353. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30354. /**
  30355. * Texture data comes from a cube data file
  30356. */
  30357. InternalTexture.DATASOURCE_CUBE = 7;
  30358. /**
  30359. * Texture data comes from a raw cube data
  30360. */
  30361. InternalTexture.DATASOURCE_CUBERAW = 8;
  30362. /**
  30363. * Texture data come from a prefiltered cube data file
  30364. */
  30365. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30366. /**
  30367. * Texture content is raw 3D data
  30368. */
  30369. InternalTexture.DATASOURCE_RAW3D = 10;
  30370. /**
  30371. * Texture content is a depth texture
  30372. */
  30373. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30374. /**
  30375. * Texture data comes from a raw cube data encoded with RGBD
  30376. */
  30377. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30378. return InternalTexture;
  30379. }());
  30380. BABYLON.InternalTexture = InternalTexture;
  30381. })(BABYLON || (BABYLON = {}));
  30382. //# sourceMappingURL=babylon.internalTexture.js.map
  30383. var BABYLON;
  30384. (function (BABYLON) {
  30385. var BaseTexture = /** @class */ (function () {
  30386. function BaseTexture(scene) {
  30387. this._hasAlpha = false;
  30388. this.getAlphaFromRGB = false;
  30389. this.level = 1;
  30390. this.coordinatesIndex = 0;
  30391. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30392. /**
  30393. * | Value | Type | Description |
  30394. * | ----- | ------------------ | ----------- |
  30395. * | 0 | CLAMP_ADDRESSMODE | |
  30396. * | 1 | WRAP_ADDRESSMODE | |
  30397. * | 2 | MIRROR_ADDRESSMODE | |
  30398. */
  30399. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30400. /**
  30401. * | Value | Type | Description |
  30402. * | ----- | ------------------ | ----------- |
  30403. * | 0 | CLAMP_ADDRESSMODE | |
  30404. * | 1 | WRAP_ADDRESSMODE | |
  30405. * | 2 | MIRROR_ADDRESSMODE | |
  30406. */
  30407. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30408. /**
  30409. * | Value | Type | Description |
  30410. * | ----- | ------------------ | ----------- |
  30411. * | 0 | CLAMP_ADDRESSMODE | |
  30412. * | 1 | WRAP_ADDRESSMODE | |
  30413. * | 2 | MIRROR_ADDRESSMODE | |
  30414. */
  30415. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30416. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30417. this.isCube = false;
  30418. this.is3D = false;
  30419. this.gammaSpace = true;
  30420. this.invertZ = false;
  30421. this.lodLevelInAlpha = false;
  30422. this.isRenderTarget = false;
  30423. this.animations = new Array();
  30424. /**
  30425. * An event triggered when the texture is disposed.
  30426. */
  30427. this.onDisposeObservable = new BABYLON.Observable();
  30428. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30429. this._cachedSize = BABYLON.Size.Zero();
  30430. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30431. if (this._scene) {
  30432. this._scene.textures.push(this);
  30433. }
  30434. this._uid = null;
  30435. }
  30436. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30437. get: function () {
  30438. return this._hasAlpha;
  30439. },
  30440. set: function (value) {
  30441. if (this._hasAlpha === value) {
  30442. return;
  30443. }
  30444. this._hasAlpha = value;
  30445. if (this._scene) {
  30446. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30447. }
  30448. },
  30449. enumerable: true,
  30450. configurable: true
  30451. });
  30452. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30453. get: function () {
  30454. return this._coordinatesMode;
  30455. },
  30456. /**
  30457. * How a texture is mapped.
  30458. *
  30459. * | Value | Type | Description |
  30460. * | ----- | ----------------------------------- | ----------- |
  30461. * | 0 | EXPLICIT_MODE | |
  30462. * | 1 | SPHERICAL_MODE | |
  30463. * | 2 | PLANAR_MODE | |
  30464. * | 3 | CUBIC_MODE | |
  30465. * | 4 | PROJECTION_MODE | |
  30466. * | 5 | SKYBOX_MODE | |
  30467. * | 6 | INVCUBIC_MODE | |
  30468. * | 7 | EQUIRECTANGULAR_MODE | |
  30469. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30470. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30471. */
  30472. set: function (value) {
  30473. if (this._coordinatesMode === value) {
  30474. return;
  30475. }
  30476. this._coordinatesMode = value;
  30477. if (this._scene) {
  30478. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30479. }
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30485. /**
  30486. * Gets whether or not the texture contains RGBD data.
  30487. */
  30488. get: function () {
  30489. return this._texture != null && this._texture._isRGBD;
  30490. },
  30491. enumerable: true,
  30492. configurable: true
  30493. });
  30494. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30495. get: function () {
  30496. if (this._texture)
  30497. return this._texture._lodGenerationOffset;
  30498. return 0.0;
  30499. },
  30500. set: function (value) {
  30501. if (this._texture)
  30502. this._texture._lodGenerationOffset = value;
  30503. },
  30504. enumerable: true,
  30505. configurable: true
  30506. });
  30507. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30508. get: function () {
  30509. if (this._texture)
  30510. return this._texture._lodGenerationScale;
  30511. return 0.0;
  30512. },
  30513. set: function (value) {
  30514. if (this._texture)
  30515. this._texture._lodGenerationScale = value;
  30516. },
  30517. enumerable: true,
  30518. configurable: true
  30519. });
  30520. Object.defineProperty(BaseTexture.prototype, "uid", {
  30521. get: function () {
  30522. if (!this._uid) {
  30523. this._uid = BABYLON.Tools.RandomId();
  30524. }
  30525. return this._uid;
  30526. },
  30527. enumerable: true,
  30528. configurable: true
  30529. });
  30530. BaseTexture.prototype.toString = function () {
  30531. return this.name;
  30532. };
  30533. BaseTexture.prototype.getClassName = function () {
  30534. return "BaseTexture";
  30535. };
  30536. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30537. set: function (callback) {
  30538. if (this._onDisposeObserver) {
  30539. this.onDisposeObservable.remove(this._onDisposeObserver);
  30540. }
  30541. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30542. },
  30543. enumerable: true,
  30544. configurable: true
  30545. });
  30546. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30547. get: function () {
  30548. return true;
  30549. },
  30550. enumerable: true,
  30551. configurable: true
  30552. });
  30553. BaseTexture.prototype.getScene = function () {
  30554. return this._scene;
  30555. };
  30556. BaseTexture.prototype.getTextureMatrix = function () {
  30557. return BABYLON.Matrix.IdentityReadOnly;
  30558. };
  30559. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30560. return BABYLON.Matrix.IdentityReadOnly;
  30561. };
  30562. BaseTexture.prototype.getInternalTexture = function () {
  30563. return this._texture;
  30564. };
  30565. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30566. return !this.isBlocking || this.isReady();
  30567. };
  30568. BaseTexture.prototype.isReady = function () {
  30569. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30570. this.delayLoad();
  30571. return false;
  30572. }
  30573. if (this._texture) {
  30574. return this._texture.isReady;
  30575. }
  30576. return false;
  30577. };
  30578. BaseTexture.prototype.getSize = function () {
  30579. if (this._texture) {
  30580. if (this._texture.width) {
  30581. this._cachedSize.width = this._texture.width;
  30582. this._cachedSize.height = this._texture.height;
  30583. return this._cachedSize;
  30584. }
  30585. if (this._texture._size) {
  30586. this._cachedSize.width = this._texture._size;
  30587. this._cachedSize.height = this._texture._size;
  30588. return this._cachedSize;
  30589. }
  30590. }
  30591. return this._cachedSize;
  30592. };
  30593. BaseTexture.prototype.getBaseSize = function () {
  30594. if (!this.isReady() || !this._texture)
  30595. return BABYLON.Size.Zero();
  30596. if (this._texture._size) {
  30597. return new BABYLON.Size(this._texture._size, this._texture._size);
  30598. }
  30599. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30600. };
  30601. BaseTexture.prototype.scale = function (ratio) {
  30602. };
  30603. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30604. get: function () {
  30605. return false;
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30611. if (!this._scene) {
  30612. return null;
  30613. }
  30614. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30615. for (var index = 0; index < texturesCache.length; index++) {
  30616. var texturesCacheEntry = texturesCache[index];
  30617. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30618. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30619. texturesCacheEntry.incrementReferences();
  30620. return texturesCacheEntry;
  30621. }
  30622. }
  30623. }
  30624. return null;
  30625. };
  30626. BaseTexture.prototype._rebuild = function () {
  30627. };
  30628. BaseTexture.prototype.delayLoad = function () {
  30629. };
  30630. BaseTexture.prototype.clone = function () {
  30631. return null;
  30632. };
  30633. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30634. get: function () {
  30635. if (!this._texture) {
  30636. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30637. }
  30638. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30639. },
  30640. enumerable: true,
  30641. configurable: true
  30642. });
  30643. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30644. get: function () {
  30645. if (!this._texture) {
  30646. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30647. }
  30648. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. /**
  30654. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30655. * This will returns an RGBA array buffer containing either in values (0-255) or
  30656. * float values (0-1) depending of the underlying buffer type.
  30657. * @param faceIndex The face of the texture to read (in case of cube texture)
  30658. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30659. * @returns The Array buffer containing the pixels data.
  30660. */
  30661. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30662. if (faceIndex === void 0) { faceIndex = 0; }
  30663. if (level === void 0) { level = 0; }
  30664. if (!this._texture) {
  30665. return null;
  30666. }
  30667. var size = this.getSize();
  30668. var width = size.width;
  30669. var height = size.height;
  30670. var scene = this.getScene();
  30671. if (!scene) {
  30672. return null;
  30673. }
  30674. var engine = scene.getEngine();
  30675. if (level != 0) {
  30676. width = width / Math.pow(2, level);
  30677. height = height / Math.pow(2, level);
  30678. width = Math.round(width);
  30679. height = Math.round(height);
  30680. }
  30681. if (this._texture.isCube) {
  30682. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30683. }
  30684. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30685. };
  30686. BaseTexture.prototype.releaseInternalTexture = function () {
  30687. if (this._texture) {
  30688. this._texture.dispose();
  30689. this._texture = null;
  30690. }
  30691. };
  30692. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30693. get: function () {
  30694. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30695. return null;
  30696. }
  30697. if (!this._texture._sphericalPolynomial) {
  30698. this._texture._sphericalPolynomial =
  30699. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30700. }
  30701. return this._texture._sphericalPolynomial;
  30702. },
  30703. set: function (value) {
  30704. if (this._texture) {
  30705. this._texture._sphericalPolynomial = value;
  30706. }
  30707. },
  30708. enumerable: true,
  30709. configurable: true
  30710. });
  30711. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30712. get: function () {
  30713. if (this._texture) {
  30714. return this._texture._lodTextureHigh;
  30715. }
  30716. return null;
  30717. },
  30718. enumerable: true,
  30719. configurable: true
  30720. });
  30721. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30722. get: function () {
  30723. if (this._texture) {
  30724. return this._texture._lodTextureMid;
  30725. }
  30726. return null;
  30727. },
  30728. enumerable: true,
  30729. configurable: true
  30730. });
  30731. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30732. get: function () {
  30733. if (this._texture) {
  30734. return this._texture._lodTextureLow;
  30735. }
  30736. return null;
  30737. },
  30738. enumerable: true,
  30739. configurable: true
  30740. });
  30741. BaseTexture.prototype.dispose = function () {
  30742. if (!this._scene) {
  30743. return;
  30744. }
  30745. // Animations
  30746. this._scene.stopAnimation(this);
  30747. // Remove from scene
  30748. this._scene._removePendingData(this);
  30749. var index = this._scene.textures.indexOf(this);
  30750. if (index >= 0) {
  30751. this._scene.textures.splice(index, 1);
  30752. }
  30753. if (this._texture === undefined) {
  30754. return;
  30755. }
  30756. // Release
  30757. this.releaseInternalTexture();
  30758. // Callback
  30759. this.onDisposeObservable.notifyObservers(this);
  30760. this.onDisposeObservable.clear();
  30761. };
  30762. BaseTexture.prototype.serialize = function () {
  30763. if (!this.name) {
  30764. return null;
  30765. }
  30766. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30767. // Animations
  30768. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30769. return serializationObject;
  30770. };
  30771. BaseTexture.WhenAllReady = function (textures, callback) {
  30772. var numRemaining = textures.length;
  30773. if (numRemaining === 0) {
  30774. callback();
  30775. return;
  30776. }
  30777. var _loop_1 = function () {
  30778. texture = textures[i];
  30779. if (texture.isReady()) {
  30780. if (--numRemaining === 0) {
  30781. callback();
  30782. }
  30783. }
  30784. else {
  30785. onLoadObservable = texture.onLoadObservable;
  30786. var onLoadCallback_1 = function () {
  30787. onLoadObservable.removeCallback(onLoadCallback_1);
  30788. if (--numRemaining === 0) {
  30789. callback();
  30790. }
  30791. };
  30792. onLoadObservable.add(onLoadCallback_1);
  30793. }
  30794. };
  30795. var texture, onLoadObservable;
  30796. for (var i = 0; i < textures.length; i++) {
  30797. _loop_1();
  30798. }
  30799. };
  30800. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30801. __decorate([
  30802. BABYLON.serialize()
  30803. ], BaseTexture.prototype, "name", void 0);
  30804. __decorate([
  30805. BABYLON.serialize("hasAlpha")
  30806. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30807. __decorate([
  30808. BABYLON.serialize()
  30809. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30810. __decorate([
  30811. BABYLON.serialize()
  30812. ], BaseTexture.prototype, "level", void 0);
  30813. __decorate([
  30814. BABYLON.serialize()
  30815. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30816. __decorate([
  30817. BABYLON.serialize("coordinatesMode")
  30818. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30819. __decorate([
  30820. BABYLON.serialize()
  30821. ], BaseTexture.prototype, "wrapU", void 0);
  30822. __decorate([
  30823. BABYLON.serialize()
  30824. ], BaseTexture.prototype, "wrapV", void 0);
  30825. __decorate([
  30826. BABYLON.serialize()
  30827. ], BaseTexture.prototype, "wrapR", void 0);
  30828. __decorate([
  30829. BABYLON.serialize()
  30830. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30831. __decorate([
  30832. BABYLON.serialize()
  30833. ], BaseTexture.prototype, "isCube", void 0);
  30834. __decorate([
  30835. BABYLON.serialize()
  30836. ], BaseTexture.prototype, "is3D", void 0);
  30837. __decorate([
  30838. BABYLON.serialize()
  30839. ], BaseTexture.prototype, "gammaSpace", void 0);
  30840. __decorate([
  30841. BABYLON.serialize()
  30842. ], BaseTexture.prototype, "invertZ", void 0);
  30843. __decorate([
  30844. BABYLON.serialize()
  30845. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30846. __decorate([
  30847. BABYLON.serialize()
  30848. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30849. __decorate([
  30850. BABYLON.serialize()
  30851. ], BaseTexture.prototype, "lodGenerationScale", null);
  30852. __decorate([
  30853. BABYLON.serialize()
  30854. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30855. return BaseTexture;
  30856. }());
  30857. BABYLON.BaseTexture = BaseTexture;
  30858. })(BABYLON || (BABYLON = {}));
  30859. //# sourceMappingURL=babylon.baseTexture.js.map
  30860. var BABYLON;
  30861. (function (BABYLON) {
  30862. var Texture = /** @class */ (function (_super) {
  30863. __extends(Texture, _super);
  30864. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30865. if (noMipmap === void 0) { noMipmap = false; }
  30866. if (invertY === void 0) { invertY = true; }
  30867. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30868. if (onLoad === void 0) { onLoad = null; }
  30869. if (onError === void 0) { onError = null; }
  30870. if (buffer === void 0) { buffer = null; }
  30871. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30872. var _this = _super.call(this, scene) || this;
  30873. _this.uOffset = 0;
  30874. _this.vOffset = 0;
  30875. _this.uScale = 1.0;
  30876. _this.vScale = 1.0;
  30877. _this.uAng = 0;
  30878. _this.vAng = 0;
  30879. _this.wAng = 0;
  30880. /**
  30881. * Defines the center of rotation (U)
  30882. */
  30883. _this.uRotationCenter = 0.5;
  30884. /**
  30885. * Defines the center of rotation (V)
  30886. */
  30887. _this.vRotationCenter = 0.5;
  30888. /**
  30889. * Defines the center of rotation (W)
  30890. */
  30891. _this.wRotationCenter = 0.5;
  30892. _this._isBlocking = true;
  30893. _this.name = url || "";
  30894. _this.url = url;
  30895. _this._noMipmap = noMipmap;
  30896. _this._invertY = invertY;
  30897. _this._samplingMode = samplingMode;
  30898. _this._buffer = buffer;
  30899. _this._deleteBuffer = deleteBuffer;
  30900. if (format) {
  30901. _this._format = format;
  30902. }
  30903. scene = _this.getScene();
  30904. if (!scene) {
  30905. return _this;
  30906. }
  30907. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30908. var load = function () {
  30909. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30910. _this.onLoadObservable.notifyObservers(_this);
  30911. }
  30912. if (onLoad) {
  30913. onLoad();
  30914. }
  30915. if (!_this.isBlocking && scene) {
  30916. scene.resetCachedMaterial();
  30917. }
  30918. };
  30919. if (!_this.url) {
  30920. _this._delayedOnLoad = load;
  30921. _this._delayedOnError = onError;
  30922. return _this;
  30923. }
  30924. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30925. if (!_this._texture) {
  30926. if (!scene.useDelayedTextureLoading) {
  30927. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30928. if (deleteBuffer) {
  30929. delete _this._buffer;
  30930. }
  30931. }
  30932. else {
  30933. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30934. _this._delayedOnLoad = load;
  30935. _this._delayedOnError = onError;
  30936. }
  30937. }
  30938. else {
  30939. if (_this._texture.isReady) {
  30940. BABYLON.Tools.SetImmediate(function () { return load(); });
  30941. }
  30942. else {
  30943. _this._texture.onLoadedObservable.add(load);
  30944. }
  30945. }
  30946. return _this;
  30947. }
  30948. Object.defineProperty(Texture.prototype, "noMipmap", {
  30949. get: function () {
  30950. return this._noMipmap;
  30951. },
  30952. enumerable: true,
  30953. configurable: true
  30954. });
  30955. Object.defineProperty(Texture.prototype, "isBlocking", {
  30956. get: function () {
  30957. return this._isBlocking;
  30958. },
  30959. set: function (value) {
  30960. this._isBlocking = value;
  30961. },
  30962. enumerable: true,
  30963. configurable: true
  30964. });
  30965. Object.defineProperty(Texture.prototype, "samplingMode", {
  30966. get: function () {
  30967. return this._samplingMode;
  30968. },
  30969. enumerable: true,
  30970. configurable: true
  30971. });
  30972. /**
  30973. * Update the url (and optional buffer) of this texture if url was null during construction.
  30974. * @param url the url of the texture
  30975. * @param buffer the buffer of the texture (defaults to null)
  30976. */
  30977. Texture.prototype.updateURL = function (url, buffer) {
  30978. if (buffer === void 0) { buffer = null; }
  30979. if (this.url) {
  30980. throw new Error("URL is already set");
  30981. }
  30982. this.url = url;
  30983. this._buffer = buffer;
  30984. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30985. this.delayLoad();
  30986. };
  30987. Texture.prototype.delayLoad = function () {
  30988. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30989. return;
  30990. }
  30991. var scene = this.getScene();
  30992. if (!scene) {
  30993. return;
  30994. }
  30995. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30996. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30997. if (!this._texture) {
  30998. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30999. if (this._deleteBuffer) {
  31000. delete this._buffer;
  31001. }
  31002. }
  31003. else {
  31004. if (this._delayedOnLoad) {
  31005. if (this._texture.isReady) {
  31006. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31007. }
  31008. else {
  31009. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31010. }
  31011. }
  31012. }
  31013. this._delayedOnLoad = null;
  31014. this._delayedOnError = null;
  31015. };
  31016. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31017. if (!this._texture) {
  31018. return;
  31019. }
  31020. var scene = this.getScene();
  31021. if (!scene) {
  31022. return;
  31023. }
  31024. this._samplingMode = samplingMode;
  31025. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31026. };
  31027. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31028. x *= this.uScale;
  31029. y *= this.vScale;
  31030. x -= this.uRotationCenter * this.uScale;
  31031. y -= this.vRotationCenter * this.vScale;
  31032. z -= this.wRotationCenter;
  31033. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31034. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31035. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31036. t.z += this.wRotationCenter;
  31037. };
  31038. Texture.prototype.getTextureMatrix = function () {
  31039. var _this = this;
  31040. if (this.uOffset === this._cachedUOffset &&
  31041. this.vOffset === this._cachedVOffset &&
  31042. this.uScale === this._cachedUScale &&
  31043. this.vScale === this._cachedVScale &&
  31044. this.uAng === this._cachedUAng &&
  31045. this.vAng === this._cachedVAng &&
  31046. this.wAng === this._cachedWAng) {
  31047. return this._cachedTextureMatrix;
  31048. }
  31049. this._cachedUOffset = this.uOffset;
  31050. this._cachedVOffset = this.vOffset;
  31051. this._cachedUScale = this.uScale;
  31052. this._cachedVScale = this.vScale;
  31053. this._cachedUAng = this.uAng;
  31054. this._cachedVAng = this.vAng;
  31055. this._cachedWAng = this.wAng;
  31056. if (!this._cachedTextureMatrix) {
  31057. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31058. this._rowGenerationMatrix = new BABYLON.Matrix();
  31059. this._t0 = BABYLON.Vector3.Zero();
  31060. this._t1 = BABYLON.Vector3.Zero();
  31061. this._t2 = BABYLON.Vector3.Zero();
  31062. }
  31063. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31064. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31065. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31066. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31067. this._t1.subtractInPlace(this._t0);
  31068. this._t2.subtractInPlace(this._t0);
  31069. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31070. this._cachedTextureMatrix.m[0] = this._t1.x;
  31071. this._cachedTextureMatrix.m[1] = this._t1.y;
  31072. this._cachedTextureMatrix.m[2] = this._t1.z;
  31073. this._cachedTextureMatrix.m[4] = this._t2.x;
  31074. this._cachedTextureMatrix.m[5] = this._t2.y;
  31075. this._cachedTextureMatrix.m[6] = this._t2.z;
  31076. this._cachedTextureMatrix.m[8] = this._t0.x;
  31077. this._cachedTextureMatrix.m[9] = this._t0.y;
  31078. this._cachedTextureMatrix.m[10] = this._t0.z;
  31079. var scene = this.getScene();
  31080. if (!scene) {
  31081. return this._cachedTextureMatrix;
  31082. }
  31083. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31084. return mat.hasTexture(_this);
  31085. });
  31086. return this._cachedTextureMatrix;
  31087. };
  31088. Texture.prototype.getReflectionTextureMatrix = function () {
  31089. var _this = this;
  31090. var scene = this.getScene();
  31091. if (!scene) {
  31092. return this._cachedTextureMatrix;
  31093. }
  31094. if (this.uOffset === this._cachedUOffset &&
  31095. this.vOffset === this._cachedVOffset &&
  31096. this.uScale === this._cachedUScale &&
  31097. this.vScale === this._cachedVScale &&
  31098. this.coordinatesMode === this._cachedCoordinatesMode) {
  31099. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31100. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31101. return this._cachedTextureMatrix;
  31102. }
  31103. }
  31104. else {
  31105. return this._cachedTextureMatrix;
  31106. }
  31107. }
  31108. if (!this._cachedTextureMatrix) {
  31109. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31110. }
  31111. if (!this._projectionModeMatrix) {
  31112. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31113. }
  31114. this._cachedUOffset = this.uOffset;
  31115. this._cachedVOffset = this.vOffset;
  31116. this._cachedUScale = this.uScale;
  31117. this._cachedVScale = this.vScale;
  31118. this._cachedCoordinatesMode = this.coordinatesMode;
  31119. switch (this.coordinatesMode) {
  31120. case Texture.PLANAR_MODE:
  31121. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31122. this._cachedTextureMatrix[0] = this.uScale;
  31123. this._cachedTextureMatrix[5] = this.vScale;
  31124. this._cachedTextureMatrix[12] = this.uOffset;
  31125. this._cachedTextureMatrix[13] = this.vOffset;
  31126. break;
  31127. case Texture.PROJECTION_MODE:
  31128. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31129. this._projectionModeMatrix.m[0] = 0.5;
  31130. this._projectionModeMatrix.m[5] = -0.5;
  31131. this._projectionModeMatrix.m[10] = 0.0;
  31132. this._projectionModeMatrix.m[12] = 0.5;
  31133. this._projectionModeMatrix.m[13] = 0.5;
  31134. this._projectionModeMatrix.m[14] = 1.0;
  31135. this._projectionModeMatrix.m[15] = 1.0;
  31136. var projectionMatrix = scene.getProjectionMatrix();
  31137. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31138. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31139. break;
  31140. default:
  31141. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31142. break;
  31143. }
  31144. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31145. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31146. });
  31147. return this._cachedTextureMatrix;
  31148. };
  31149. Texture.prototype.clone = function () {
  31150. var _this = this;
  31151. return BABYLON.SerializationHelper.Clone(function () {
  31152. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31153. }, this);
  31154. };
  31155. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31156. get: function () {
  31157. if (!this._onLoadObservable) {
  31158. this._onLoadObservable = new BABYLON.Observable();
  31159. }
  31160. return this._onLoadObservable;
  31161. },
  31162. enumerable: true,
  31163. configurable: true
  31164. });
  31165. Texture.prototype.serialize = function () {
  31166. var serializationObject = _super.prototype.serialize.call(this);
  31167. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31168. serializationObject.base64String = this._buffer;
  31169. serializationObject.name = serializationObject.name.replace("data:", "");
  31170. }
  31171. serializationObject.invertY = this._invertY;
  31172. serializationObject.samplingMode = this.samplingMode;
  31173. return serializationObject;
  31174. };
  31175. Texture.prototype.getClassName = function () {
  31176. return "Texture";
  31177. };
  31178. Texture.prototype.dispose = function () {
  31179. _super.prototype.dispose.call(this);
  31180. if (this._onLoadObservable) {
  31181. this._onLoadObservable.clear();
  31182. this._onLoadObservable = null;
  31183. }
  31184. this._delayedOnLoad = null;
  31185. this._delayedOnError = null;
  31186. };
  31187. // Statics
  31188. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31189. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31190. if (onLoad === void 0) { onLoad = null; }
  31191. if (onError === void 0) { onError = null; }
  31192. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31193. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31194. };
  31195. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31196. if (parsedTexture.customType) {
  31197. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31198. // Update Sampling Mode
  31199. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31200. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31201. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31202. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31203. }
  31204. }
  31205. return parsedCustomTexture;
  31206. }
  31207. if (parsedTexture.isCube) {
  31208. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31209. }
  31210. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31211. return null;
  31212. }
  31213. var texture = BABYLON.SerializationHelper.Parse(function () {
  31214. var generateMipMaps = true;
  31215. if (parsedTexture.noMipmap) {
  31216. generateMipMaps = false;
  31217. }
  31218. if (parsedTexture.mirrorPlane) {
  31219. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31220. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31221. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31222. return mirrorTexture;
  31223. }
  31224. else if (parsedTexture.isRenderTarget) {
  31225. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31226. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31227. return renderTargetTexture;
  31228. }
  31229. else {
  31230. var texture;
  31231. if (parsedTexture.base64String) {
  31232. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31233. }
  31234. else {
  31235. var url = rootUrl + parsedTexture.name;
  31236. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31237. url = parsedTexture.url;
  31238. }
  31239. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31240. }
  31241. return texture;
  31242. }
  31243. }, parsedTexture, scene);
  31244. // Update Sampling Mode
  31245. if (parsedTexture.samplingMode) {
  31246. var sampling = parsedTexture.samplingMode;
  31247. if (texture._samplingMode !== sampling) {
  31248. texture.updateSamplingMode(sampling);
  31249. }
  31250. }
  31251. // Animations
  31252. if (parsedTexture.animations) {
  31253. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31254. var parsedAnimation = parsedTexture.animations[animationIndex];
  31255. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31256. }
  31257. }
  31258. return texture;
  31259. };
  31260. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31261. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31262. if (noMipmap === void 0) { noMipmap = false; }
  31263. if (invertY === void 0) { invertY = true; }
  31264. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31265. if (onLoad === void 0) { onLoad = null; }
  31266. if (onError === void 0) { onError = null; }
  31267. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31268. if (name.substr(0, 5) !== "data:") {
  31269. name = "data:" + name;
  31270. }
  31271. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31272. };
  31273. // Constants
  31274. Texture.NEAREST_SAMPLINGMODE = 1;
  31275. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31276. Texture.BILINEAR_SAMPLINGMODE = 2;
  31277. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31278. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31279. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31280. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31281. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31282. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31283. Texture.NEAREST_LINEAR = 7;
  31284. Texture.NEAREST_NEAREST = 8;
  31285. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31286. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31287. Texture.LINEAR_LINEAR = 11;
  31288. Texture.LINEAR_NEAREST = 12;
  31289. Texture.EXPLICIT_MODE = 0;
  31290. Texture.SPHERICAL_MODE = 1;
  31291. Texture.PLANAR_MODE = 2;
  31292. Texture.CUBIC_MODE = 3;
  31293. Texture.PROJECTION_MODE = 4;
  31294. Texture.SKYBOX_MODE = 5;
  31295. Texture.INVCUBIC_MODE = 6;
  31296. Texture.EQUIRECTANGULAR_MODE = 7;
  31297. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31298. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31299. Texture.CLAMP_ADDRESSMODE = 0;
  31300. Texture.WRAP_ADDRESSMODE = 1;
  31301. Texture.MIRROR_ADDRESSMODE = 2;
  31302. /**
  31303. * 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
  31304. */
  31305. Texture.UseSerializedUrlIfAny = false;
  31306. __decorate([
  31307. BABYLON.serialize()
  31308. ], Texture.prototype, "url", void 0);
  31309. __decorate([
  31310. BABYLON.serialize()
  31311. ], Texture.prototype, "uOffset", void 0);
  31312. __decorate([
  31313. BABYLON.serialize()
  31314. ], Texture.prototype, "vOffset", void 0);
  31315. __decorate([
  31316. BABYLON.serialize()
  31317. ], Texture.prototype, "uScale", void 0);
  31318. __decorate([
  31319. BABYLON.serialize()
  31320. ], Texture.prototype, "vScale", void 0);
  31321. __decorate([
  31322. BABYLON.serialize()
  31323. ], Texture.prototype, "uAng", void 0);
  31324. __decorate([
  31325. BABYLON.serialize()
  31326. ], Texture.prototype, "vAng", void 0);
  31327. __decorate([
  31328. BABYLON.serialize()
  31329. ], Texture.prototype, "wAng", void 0);
  31330. __decorate([
  31331. BABYLON.serialize()
  31332. ], Texture.prototype, "uRotationCenter", void 0);
  31333. __decorate([
  31334. BABYLON.serialize()
  31335. ], Texture.prototype, "vRotationCenter", void 0);
  31336. __decorate([
  31337. BABYLON.serialize()
  31338. ], Texture.prototype, "wRotationCenter", void 0);
  31339. __decorate([
  31340. BABYLON.serialize()
  31341. ], Texture.prototype, "isBlocking", null);
  31342. return Texture;
  31343. }(BABYLON.BaseTexture));
  31344. BABYLON.Texture = Texture;
  31345. })(BABYLON || (BABYLON = {}));
  31346. //# sourceMappingURL=babylon.texture.js.map
  31347. var BABYLON;
  31348. (function (BABYLON) {
  31349. /**
  31350. * @hidden
  31351. **/
  31352. var _InstancesBatch = /** @class */ (function () {
  31353. function _InstancesBatch() {
  31354. this.mustReturn = false;
  31355. this.visibleInstances = new Array();
  31356. this.renderSelf = new Array();
  31357. }
  31358. return _InstancesBatch;
  31359. }());
  31360. BABYLON._InstancesBatch = _InstancesBatch;
  31361. var Mesh = /** @class */ (function (_super) {
  31362. __extends(Mesh, _super);
  31363. /**
  31364. * @constructor
  31365. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31366. * @param {Scene} scene The scene to add this mesh to.
  31367. * @param {Node} parent The parent of this mesh, if it has one
  31368. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31369. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31370. * When false, achieved by calling a clone(), also passing False.
  31371. * This will make creation of children, recursive.
  31372. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31373. */
  31374. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31375. if (scene === void 0) { scene = null; }
  31376. if (parent === void 0) { parent = null; }
  31377. if (source === void 0) { source = null; }
  31378. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31379. var _this = _super.call(this, name, scene) || this;
  31380. // Events
  31381. /**
  31382. * An event triggered before rendering the mesh
  31383. */
  31384. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31385. /**
  31386. * An event triggered after rendering the mesh
  31387. */
  31388. _this.onAfterRenderObservable = new BABYLON.Observable();
  31389. /**
  31390. * An event triggered before drawing the mesh
  31391. */
  31392. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31393. // Members
  31394. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31395. _this.instances = new Array();
  31396. _this._LODLevels = new Array();
  31397. _this._visibleInstances = {};
  31398. _this._renderIdForInstances = new Array();
  31399. _this._batchCache = new _InstancesBatch();
  31400. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31401. // Use by builder only to know what orientation were the mesh build in.
  31402. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31403. _this.overrideMaterialSideOrientation = null;
  31404. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31405. // Will be used to save a source mesh reference, If any
  31406. _this._source = null;
  31407. scene = _this.getScene();
  31408. if (source) {
  31409. // Geometry
  31410. if (source._geometry) {
  31411. source._geometry.applyToMesh(_this);
  31412. }
  31413. // Deep copy
  31414. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31415. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31416. // Source mesh
  31417. _this._source = source;
  31418. // Metadata
  31419. if (source.metadata && source.metadata.clone) {
  31420. _this.metadata = source.metadata.clone();
  31421. }
  31422. else {
  31423. _this.metadata = source.metadata;
  31424. }
  31425. // Tags
  31426. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31427. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31428. }
  31429. // Parent
  31430. _this.parent = source.parent;
  31431. // Pivot
  31432. _this.setPivotMatrix(source.getPivotMatrix());
  31433. _this.id = name + "." + source.id;
  31434. // Material
  31435. _this.material = source.material;
  31436. var index;
  31437. if (!doNotCloneChildren) {
  31438. // Children
  31439. var directDescendants = source.getDescendants(true);
  31440. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31441. var child = directDescendants[index_1];
  31442. if (child.clone) {
  31443. child.clone(name + "." + child.name, _this);
  31444. }
  31445. }
  31446. }
  31447. // Physics clone
  31448. var physicsEngine = _this.getScene().getPhysicsEngine();
  31449. if (clonePhysicsImpostor && physicsEngine) {
  31450. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31451. if (impostor) {
  31452. _this.physicsImpostor = impostor.clone(_this);
  31453. }
  31454. }
  31455. // Particles
  31456. for (index = 0; index < scene.particleSystems.length; index++) {
  31457. var system = scene.particleSystems[index];
  31458. if (system.emitter === source) {
  31459. system.clone(system.name, _this);
  31460. }
  31461. }
  31462. _this.refreshBoundingInfo();
  31463. _this.computeWorldMatrix(true);
  31464. }
  31465. // Parent
  31466. if (parent !== null) {
  31467. _this.parent = parent;
  31468. }
  31469. return _this;
  31470. }
  31471. Object.defineProperty(Mesh, "FRONTSIDE", {
  31472. /**
  31473. * Mesh side orientation : usually the external or front surface
  31474. */
  31475. get: function () {
  31476. return Mesh._FRONTSIDE;
  31477. },
  31478. enumerable: true,
  31479. configurable: true
  31480. });
  31481. Object.defineProperty(Mesh, "BACKSIDE", {
  31482. /**
  31483. * Mesh side orientation : usually the internal or back surface
  31484. */
  31485. get: function () {
  31486. return Mesh._BACKSIDE;
  31487. },
  31488. enumerable: true,
  31489. configurable: true
  31490. });
  31491. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31492. /**
  31493. * Mesh side orientation : both internal and external or front and back surfaces
  31494. */
  31495. get: function () {
  31496. return Mesh._DOUBLESIDE;
  31497. },
  31498. enumerable: true,
  31499. configurable: true
  31500. });
  31501. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31502. /**
  31503. * Mesh side orientation : by default, `FRONTSIDE`
  31504. */
  31505. get: function () {
  31506. return Mesh._DEFAULTSIDE;
  31507. },
  31508. enumerable: true,
  31509. configurable: true
  31510. });
  31511. Object.defineProperty(Mesh, "NO_CAP", {
  31512. /**
  31513. * Mesh cap setting : no cap
  31514. */
  31515. get: function () {
  31516. return Mesh._NO_CAP;
  31517. },
  31518. enumerable: true,
  31519. configurable: true
  31520. });
  31521. Object.defineProperty(Mesh, "CAP_START", {
  31522. /**
  31523. * Mesh cap setting : one cap at the beginning of the mesh
  31524. */
  31525. get: function () {
  31526. return Mesh._CAP_START;
  31527. },
  31528. enumerable: true,
  31529. configurable: true
  31530. });
  31531. Object.defineProperty(Mesh, "CAP_END", {
  31532. /**
  31533. * Mesh cap setting : one cap at the end of the mesh
  31534. */
  31535. get: function () {
  31536. return Mesh._CAP_END;
  31537. },
  31538. enumerable: true,
  31539. configurable: true
  31540. });
  31541. Object.defineProperty(Mesh, "CAP_ALL", {
  31542. /**
  31543. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31544. */
  31545. get: function () {
  31546. return Mesh._CAP_ALL;
  31547. },
  31548. enumerable: true,
  31549. configurable: true
  31550. });
  31551. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31552. set: function (callback) {
  31553. if (this._onBeforeDrawObserver) {
  31554. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31555. }
  31556. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31557. },
  31558. enumerable: true,
  31559. configurable: true
  31560. });
  31561. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31562. get: function () {
  31563. return this._morphTargetManager;
  31564. },
  31565. set: function (value) {
  31566. if (this._morphTargetManager === value) {
  31567. return;
  31568. }
  31569. this._morphTargetManager = value;
  31570. this._syncGeometryWithMorphTargetManager();
  31571. },
  31572. enumerable: true,
  31573. configurable: true
  31574. });
  31575. Object.defineProperty(Mesh.prototype, "source", {
  31576. get: function () {
  31577. return this._source;
  31578. },
  31579. enumerable: true,
  31580. configurable: true
  31581. });
  31582. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31583. get: function () {
  31584. return this._unIndexed;
  31585. },
  31586. set: function (value) {
  31587. if (this._unIndexed !== value) {
  31588. this._unIndexed = value;
  31589. this._markSubMeshesAsAttributesDirty();
  31590. }
  31591. },
  31592. enumerable: true,
  31593. configurable: true
  31594. });
  31595. // Methods
  31596. /**
  31597. * Returns the string "Mesh".
  31598. */
  31599. Mesh.prototype.getClassName = function () {
  31600. return "Mesh";
  31601. };
  31602. /**
  31603. * Returns a string.
  31604. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31605. */
  31606. Mesh.prototype.toString = function (fullDetails) {
  31607. var ret = _super.prototype.toString.call(this, fullDetails);
  31608. ret += ", n vertices: " + this.getTotalVertices();
  31609. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31610. if (this.animations) {
  31611. for (var i = 0; i < this.animations.length; i++) {
  31612. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31613. }
  31614. }
  31615. if (fullDetails) {
  31616. if (this._geometry) {
  31617. var ib = this.getIndices();
  31618. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31619. if (vb && ib) {
  31620. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31621. }
  31622. }
  31623. else {
  31624. ret += ", flat shading: UNKNOWN";
  31625. }
  31626. }
  31627. return ret;
  31628. };
  31629. Mesh.prototype._unBindEffect = function () {
  31630. _super.prototype._unBindEffect.call(this);
  31631. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31632. var instance = _a[_i];
  31633. instance._unBindEffect();
  31634. }
  31635. };
  31636. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31637. /**
  31638. * True if the mesh has some Levels Of Details (LOD).
  31639. * Returns a boolean.
  31640. */
  31641. get: function () {
  31642. return this._LODLevels.length > 0;
  31643. },
  31644. enumerable: true,
  31645. configurable: true
  31646. });
  31647. /**
  31648. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31649. * @returns an array of {BABYLON.MeshLODLevel}
  31650. */
  31651. Mesh.prototype.getLODLevels = function () {
  31652. return this._LODLevels;
  31653. };
  31654. Mesh.prototype._sortLODLevels = function () {
  31655. this._LODLevels.sort(function (a, b) {
  31656. if (a.distance < b.distance) {
  31657. return 1;
  31658. }
  31659. if (a.distance > b.distance) {
  31660. return -1;
  31661. }
  31662. return 0;
  31663. });
  31664. };
  31665. /**
  31666. * Add a mesh as LOD level triggered at the given distance.
  31667. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31668. * @param distance The distance from the center of the object to show this level
  31669. * @param mesh The mesh to be added as LOD level (can be null)
  31670. * @return This mesh (for chaining)
  31671. */
  31672. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31673. if (mesh && mesh._masterMesh) {
  31674. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31675. return this;
  31676. }
  31677. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31678. this._LODLevels.push(level);
  31679. if (mesh) {
  31680. mesh._masterMesh = this;
  31681. }
  31682. this._sortLODLevels();
  31683. return this;
  31684. };
  31685. /**
  31686. * Returns the LOD level mesh at the passed distance or null if not found.
  31687. * It is related to the method `addLODLevel(distance, mesh)`.
  31688. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31689. * Returns an object Mesh or `null`.
  31690. */
  31691. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31692. for (var index = 0; index < this._LODLevels.length; index++) {
  31693. var level = this._LODLevels[index];
  31694. if (level.distance === distance) {
  31695. return level.mesh;
  31696. }
  31697. }
  31698. return null;
  31699. };
  31700. /**
  31701. * Remove a mesh from the LOD array
  31702. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31703. * @param {Mesh} mesh The mesh to be removed.
  31704. * @return {Mesh} This mesh (for chaining)
  31705. */
  31706. Mesh.prototype.removeLODLevel = function (mesh) {
  31707. for (var index = 0; index < this._LODLevels.length; index++) {
  31708. if (this._LODLevels[index].mesh === mesh) {
  31709. this._LODLevels.splice(index, 1);
  31710. if (mesh) {
  31711. mesh._masterMesh = null;
  31712. }
  31713. }
  31714. }
  31715. this._sortLODLevels();
  31716. return this;
  31717. };
  31718. /**
  31719. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31720. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31721. */
  31722. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31723. if (!this._LODLevels || this._LODLevels.length === 0) {
  31724. return this;
  31725. }
  31726. var bSphere;
  31727. if (boundingSphere) {
  31728. bSphere = boundingSphere;
  31729. }
  31730. else {
  31731. var boundingInfo = this.getBoundingInfo();
  31732. bSphere = boundingInfo.boundingSphere;
  31733. }
  31734. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31735. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31736. if (this.onLODLevelSelection) {
  31737. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31738. }
  31739. return this;
  31740. }
  31741. for (var index = 0; index < this._LODLevels.length; index++) {
  31742. var level = this._LODLevels[index];
  31743. if (level.distance < distanceToCamera) {
  31744. if (level.mesh) {
  31745. level.mesh._preActivate();
  31746. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31747. }
  31748. if (this.onLODLevelSelection) {
  31749. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31750. }
  31751. return level.mesh;
  31752. }
  31753. }
  31754. if (this.onLODLevelSelection) {
  31755. this.onLODLevelSelection(distanceToCamera, this, this);
  31756. }
  31757. return this;
  31758. };
  31759. Object.defineProperty(Mesh.prototype, "geometry", {
  31760. /**
  31761. * Returns the mesh internal Geometry object.
  31762. */
  31763. get: function () {
  31764. return this._geometry;
  31765. },
  31766. enumerable: true,
  31767. configurable: true
  31768. });
  31769. /**
  31770. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31771. */
  31772. Mesh.prototype.getTotalVertices = function () {
  31773. if (this._geometry === null || this._geometry === undefined) {
  31774. return 0;
  31775. }
  31776. return this._geometry.getTotalVertices();
  31777. };
  31778. /**
  31779. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31780. * 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.
  31781. * You can force the copy with forceCopy === true
  31782. * Returns null if the mesh has no geometry or no vertex buffer.
  31783. * Possible `kind` values :
  31784. * - BABYLON.VertexBuffer.PositionKind
  31785. * - BABYLON.VertexBuffer.UVKind
  31786. * - BABYLON.VertexBuffer.UV2Kind
  31787. * - BABYLON.VertexBuffer.UV3Kind
  31788. * - BABYLON.VertexBuffer.UV4Kind
  31789. * - BABYLON.VertexBuffer.UV5Kind
  31790. * - BABYLON.VertexBuffer.UV6Kind
  31791. * - BABYLON.VertexBuffer.ColorKind
  31792. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31793. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31794. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31795. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31796. */
  31797. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31798. if (!this._geometry) {
  31799. return null;
  31800. }
  31801. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31802. };
  31803. /**
  31804. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31805. * Returns `null` if the mesh has no geometry.
  31806. * Possible `kind` values :
  31807. * - BABYLON.VertexBuffer.PositionKind
  31808. * - BABYLON.VertexBuffer.UVKind
  31809. * - BABYLON.VertexBuffer.UV2Kind
  31810. * - BABYLON.VertexBuffer.UV3Kind
  31811. * - BABYLON.VertexBuffer.UV4Kind
  31812. * - BABYLON.VertexBuffer.UV5Kind
  31813. * - BABYLON.VertexBuffer.UV6Kind
  31814. * - BABYLON.VertexBuffer.ColorKind
  31815. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31816. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31817. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31818. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31819. */
  31820. Mesh.prototype.getVertexBuffer = function (kind) {
  31821. if (!this._geometry) {
  31822. return null;
  31823. }
  31824. return this._geometry.getVertexBuffer(kind);
  31825. };
  31826. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31827. if (!this._geometry) {
  31828. if (this._delayInfo) {
  31829. return this._delayInfo.indexOf(kind) !== -1;
  31830. }
  31831. return false;
  31832. }
  31833. return this._geometry.isVerticesDataPresent(kind);
  31834. };
  31835. /**
  31836. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31837. * Possible `kind` values :
  31838. * - BABYLON.VertexBuffer.PositionKind
  31839. * - BABYLON.VertexBuffer.UVKind
  31840. * - BABYLON.VertexBuffer.UV2Kind
  31841. * - BABYLON.VertexBuffer.UV3Kind
  31842. * - BABYLON.VertexBuffer.UV4Kind
  31843. * - BABYLON.VertexBuffer.UV5Kind
  31844. * - BABYLON.VertexBuffer.UV6Kind
  31845. * - BABYLON.VertexBuffer.ColorKind
  31846. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31847. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31848. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31849. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31850. */
  31851. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31852. if (!this._geometry) {
  31853. if (this._delayInfo) {
  31854. return this._delayInfo.indexOf(kind) !== -1;
  31855. }
  31856. return false;
  31857. }
  31858. return this._geometry.isVertexBufferUpdatable(kind);
  31859. };
  31860. /**
  31861. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31862. * Possible `kind` values :
  31863. * - BABYLON.VertexBuffer.PositionKind
  31864. * - BABYLON.VertexBuffer.UVKind
  31865. * - BABYLON.VertexBuffer.UV2Kind
  31866. * - BABYLON.VertexBuffer.UV3Kind
  31867. * - BABYLON.VertexBuffer.UV4Kind
  31868. * - BABYLON.VertexBuffer.UV5Kind
  31869. * - BABYLON.VertexBuffer.UV6Kind
  31870. * - BABYLON.VertexBuffer.ColorKind
  31871. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31872. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31873. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31874. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31875. */
  31876. Mesh.prototype.getVerticesDataKinds = function () {
  31877. if (!this._geometry) {
  31878. var result = new Array();
  31879. if (this._delayInfo) {
  31880. this._delayInfo.forEach(function (kind, index, array) {
  31881. result.push(kind);
  31882. });
  31883. }
  31884. return result;
  31885. }
  31886. return this._geometry.getVerticesDataKinds();
  31887. };
  31888. /**
  31889. * Returns a positive integer : the total number of indices in this mesh geometry.
  31890. * Returns zero if the mesh has no geometry.
  31891. */
  31892. Mesh.prototype.getTotalIndices = function () {
  31893. if (!this._geometry) {
  31894. return 0;
  31895. }
  31896. return this._geometry.getTotalIndices();
  31897. };
  31898. /**
  31899. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31900. * 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.
  31901. * Returns an empty array if the mesh has no geometry.
  31902. */
  31903. Mesh.prototype.getIndices = function (copyWhenShared) {
  31904. if (!this._geometry) {
  31905. return [];
  31906. }
  31907. return this._geometry.getIndices(copyWhenShared);
  31908. };
  31909. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31910. get: function () {
  31911. return this._masterMesh !== null && this._masterMesh !== undefined;
  31912. },
  31913. enumerable: true,
  31914. configurable: true
  31915. });
  31916. /**
  31917. * Determine if the current mesh is ready to be rendered
  31918. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31919. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31920. * @returns true if all associated assets are ready (material, textures, shaders)
  31921. */
  31922. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31923. if (completeCheck === void 0) { completeCheck = false; }
  31924. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31925. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31926. return false;
  31927. }
  31928. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31929. return false;
  31930. }
  31931. if (!this.subMeshes || this.subMeshes.length === 0) {
  31932. return true;
  31933. }
  31934. if (!completeCheck) {
  31935. return true;
  31936. }
  31937. var engine = this.getEngine();
  31938. var scene = this.getScene();
  31939. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31940. this.computeWorldMatrix();
  31941. var mat = this.material || scene.defaultMaterial;
  31942. if (mat) {
  31943. if (mat.storeEffectOnSubMeshes) {
  31944. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31945. var subMesh = _a[_i];
  31946. var effectiveMaterial = subMesh.getMaterial();
  31947. if (effectiveMaterial) {
  31948. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31949. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31950. return false;
  31951. }
  31952. }
  31953. else {
  31954. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31955. return false;
  31956. }
  31957. }
  31958. }
  31959. }
  31960. }
  31961. else {
  31962. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31963. return false;
  31964. }
  31965. }
  31966. }
  31967. // Shadows
  31968. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31969. var light = _c[_b];
  31970. var generator = light.getShadowGenerator();
  31971. if (generator) {
  31972. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31973. var subMesh = _e[_d];
  31974. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31975. return false;
  31976. }
  31977. }
  31978. }
  31979. }
  31980. // LOD
  31981. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31982. var lod = _g[_f];
  31983. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31984. return false;
  31985. }
  31986. }
  31987. return true;
  31988. };
  31989. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31990. /**
  31991. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31992. * This property is pertinent only for updatable parametric shapes.
  31993. */
  31994. get: function () {
  31995. return this._areNormalsFrozen;
  31996. },
  31997. enumerable: true,
  31998. configurable: true
  31999. });
  32000. /**
  32001. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32002. * It has no effect at all on other shapes.
  32003. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32004. * Returns the Mesh.
  32005. */
  32006. Mesh.prototype.freezeNormals = function () {
  32007. this._areNormalsFrozen = true;
  32008. return this;
  32009. };
  32010. /**
  32011. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32012. * It has no effect at all on other shapes.
  32013. * It reactivates the mesh normals computation if it was previously frozen.
  32014. * Returns the Mesh.
  32015. */
  32016. Mesh.prototype.unfreezeNormals = function () {
  32017. this._areNormalsFrozen = false;
  32018. return this;
  32019. };
  32020. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32021. /**
  32022. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32023. */
  32024. set: function (count) {
  32025. this._overridenInstanceCount = count;
  32026. },
  32027. enumerable: true,
  32028. configurable: true
  32029. });
  32030. // Methods
  32031. Mesh.prototype._preActivate = function () {
  32032. var sceneRenderId = this.getScene().getRenderId();
  32033. if (this._preActivateId === sceneRenderId) {
  32034. return this;
  32035. }
  32036. this._preActivateId = sceneRenderId;
  32037. this._visibleInstances = null;
  32038. return this;
  32039. };
  32040. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32041. if (this._visibleInstances) {
  32042. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32043. }
  32044. return this;
  32045. };
  32046. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32047. if (!this._visibleInstances) {
  32048. this._visibleInstances = {};
  32049. this._visibleInstances.defaultRenderId = renderId;
  32050. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32051. }
  32052. if (!this._visibleInstances[renderId]) {
  32053. this._visibleInstances[renderId] = new Array();
  32054. }
  32055. this._visibleInstances[renderId].push(instance);
  32056. return this;
  32057. };
  32058. /**
  32059. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32060. * This means the mesh underlying bounding box and sphere are recomputed.
  32061. * Returns the Mesh.
  32062. */
  32063. Mesh.prototype.refreshBoundingInfo = function () {
  32064. return this._refreshBoundingInfo(false);
  32065. };
  32066. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32067. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32068. return this;
  32069. }
  32070. var data = this._getPositionData(applySkeleton);
  32071. if (data) {
  32072. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32073. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32074. }
  32075. if (this.subMeshes) {
  32076. for (var index = 0; index < this.subMeshes.length; index++) {
  32077. this.subMeshes[index].refreshBoundingInfo();
  32078. }
  32079. }
  32080. this._updateBoundingInfo();
  32081. return this;
  32082. };
  32083. Mesh.prototype._getPositionData = function (applySkeleton) {
  32084. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32085. if (data && applySkeleton && this.skeleton) {
  32086. data = BABYLON.Tools.Slice(data);
  32087. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32088. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32089. if (matricesWeightsData && matricesIndicesData) {
  32090. var needExtras = this.numBoneInfluencers > 4;
  32091. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32092. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32093. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32094. var tempVector = BABYLON.Tmp.Vector3[0];
  32095. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32096. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32097. var matWeightIdx = 0;
  32098. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32099. finalMatrix.reset();
  32100. var inf;
  32101. var weight;
  32102. for (inf = 0; inf < 4; inf++) {
  32103. weight = matricesWeightsData[matWeightIdx + inf];
  32104. if (weight > 0) {
  32105. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32106. finalMatrix.addToSelf(tempMatrix);
  32107. }
  32108. }
  32109. if (needExtras) {
  32110. for (inf = 0; inf < 4; inf++) {
  32111. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32112. if (weight > 0) {
  32113. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32114. finalMatrix.addToSelf(tempMatrix);
  32115. }
  32116. }
  32117. }
  32118. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32119. tempVector.toArray(data, index);
  32120. }
  32121. }
  32122. }
  32123. return data;
  32124. };
  32125. Mesh.prototype._createGlobalSubMesh = function (force) {
  32126. var totalVertices = this.getTotalVertices();
  32127. if (!totalVertices || !this.getIndices()) {
  32128. return null;
  32129. }
  32130. // Check if we need to recreate the submeshes
  32131. if (this.subMeshes && this.subMeshes.length > 0) {
  32132. var ib = this.getIndices();
  32133. if (!ib) {
  32134. return null;
  32135. }
  32136. var totalIndices = ib.length;
  32137. var needToRecreate = false;
  32138. if (force) {
  32139. needToRecreate = true;
  32140. }
  32141. else {
  32142. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32143. var submesh = _a[_i];
  32144. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32145. needToRecreate = true;
  32146. break;
  32147. }
  32148. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32149. needToRecreate = true;
  32150. break;
  32151. }
  32152. }
  32153. }
  32154. if (!needToRecreate) {
  32155. return this.subMeshes[0];
  32156. }
  32157. }
  32158. this.releaseSubMeshes();
  32159. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32160. };
  32161. Mesh.prototype.subdivide = function (count) {
  32162. if (count < 1) {
  32163. return;
  32164. }
  32165. var totalIndices = this.getTotalIndices();
  32166. var subdivisionSize = (totalIndices / count) | 0;
  32167. var offset = 0;
  32168. // Ensure that subdivisionSize is a multiple of 3
  32169. while (subdivisionSize % 3 !== 0) {
  32170. subdivisionSize++;
  32171. }
  32172. this.releaseSubMeshes();
  32173. for (var index = 0; index < count; index++) {
  32174. if (offset >= totalIndices) {
  32175. break;
  32176. }
  32177. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32178. offset += subdivisionSize;
  32179. }
  32180. this.synchronizeInstances();
  32181. };
  32182. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32183. if (updatable === void 0) { updatable = false; }
  32184. if (!this._geometry) {
  32185. var vertexData = new BABYLON.VertexData();
  32186. vertexData.set(data, kind);
  32187. var scene = this.getScene();
  32188. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32189. }
  32190. else {
  32191. this._geometry.setVerticesData(kind, data, updatable, stride);
  32192. }
  32193. return this;
  32194. };
  32195. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32196. if (updatable === void 0) { updatable = true; }
  32197. var vb = this.getVertexBuffer(kind);
  32198. if (!vb || vb.isUpdatable() === updatable) {
  32199. return;
  32200. }
  32201. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32202. };
  32203. /**
  32204. * Sets the mesh VertexBuffer.
  32205. * Returns the Mesh.
  32206. */
  32207. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32208. if (!this._geometry) {
  32209. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32210. }
  32211. this._geometry.setVerticesBuffer(buffer);
  32212. return this;
  32213. };
  32214. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32215. if (!this._geometry) {
  32216. return this;
  32217. }
  32218. if (!makeItUnique) {
  32219. this._geometry.updateVerticesData(kind, data, updateExtends);
  32220. }
  32221. else {
  32222. this.makeGeometryUnique();
  32223. this.updateVerticesData(kind, data, updateExtends, false);
  32224. }
  32225. return this;
  32226. };
  32227. /**
  32228. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32229. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32230. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32231. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32232. * Returns the Mesh.
  32233. */
  32234. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32235. if (computeNormals === void 0) { computeNormals = true; }
  32236. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32237. if (!positions) {
  32238. return this;
  32239. }
  32240. positionFunction(positions);
  32241. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32242. if (computeNormals) {
  32243. var indices = this.getIndices();
  32244. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32245. if (!normals) {
  32246. return this;
  32247. }
  32248. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32249. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32250. }
  32251. return this;
  32252. };
  32253. /**
  32254. * Creates a un-shared specific occurence of the geometry for the mesh.
  32255. * Returns the Mesh.
  32256. */
  32257. Mesh.prototype.makeGeometryUnique = function () {
  32258. if (!this._geometry) {
  32259. return this;
  32260. }
  32261. var oldGeometry = this._geometry;
  32262. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32263. oldGeometry.releaseForMesh(this, true);
  32264. geometry.applyToMesh(this);
  32265. return this;
  32266. };
  32267. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32268. if (totalVertices === void 0) { totalVertices = null; }
  32269. if (updatable === void 0) { updatable = false; }
  32270. if (!this._geometry) {
  32271. var vertexData = new BABYLON.VertexData();
  32272. vertexData.indices = indices;
  32273. var scene = this.getScene();
  32274. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32275. }
  32276. else {
  32277. this._geometry.setIndices(indices, totalVertices, updatable);
  32278. }
  32279. return this;
  32280. };
  32281. /**
  32282. * Update the current index buffer
  32283. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32284. * Returns the Mesh.
  32285. */
  32286. Mesh.prototype.updateIndices = function (indices, offset) {
  32287. if (!this._geometry) {
  32288. return this;
  32289. }
  32290. this._geometry.updateIndices(indices, offset);
  32291. return this;
  32292. };
  32293. /**
  32294. * Invert the geometry to move from a right handed system to a left handed one.
  32295. * Returns the Mesh.
  32296. */
  32297. Mesh.prototype.toLeftHanded = function () {
  32298. if (!this._geometry) {
  32299. return this;
  32300. }
  32301. this._geometry.toLeftHanded();
  32302. return this;
  32303. };
  32304. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32305. if (!this._geometry) {
  32306. return this;
  32307. }
  32308. var engine = this.getScene().getEngine();
  32309. // Wireframe
  32310. var indexToBind;
  32311. if (this._unIndexed) {
  32312. indexToBind = null;
  32313. }
  32314. else {
  32315. switch (fillMode) {
  32316. case BABYLON.Material.PointFillMode:
  32317. indexToBind = null;
  32318. break;
  32319. case BABYLON.Material.WireFrameFillMode:
  32320. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32321. break;
  32322. default:
  32323. case BABYLON.Material.TriangleFillMode:
  32324. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32325. break;
  32326. }
  32327. }
  32328. // VBOs
  32329. this._geometry._bind(effect, indexToBind);
  32330. return this;
  32331. };
  32332. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32333. if (alternate === void 0) { alternate = false; }
  32334. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32335. return this;
  32336. }
  32337. this.onBeforeDrawObservable.notifyObservers(this);
  32338. var scene = this.getScene();
  32339. var engine = scene.getEngine();
  32340. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32341. // or triangles as points
  32342. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32343. }
  32344. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32345. // Triangles as wireframe
  32346. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32347. }
  32348. else {
  32349. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32350. }
  32351. if (scene._isAlternateRenderingEnabled && !alternate) {
  32352. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32353. if (!effect || !scene.activeCamera) {
  32354. return this;
  32355. }
  32356. scene._switchToAlternateCameraConfiguration(true);
  32357. this._effectiveMaterial.bindView(effect);
  32358. this._effectiveMaterial.bindViewProjection(effect);
  32359. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32360. this._draw(subMesh, fillMode, instancesCount, true);
  32361. engine.setViewport(scene.activeCamera.viewport);
  32362. scene._switchToAlternateCameraConfiguration(false);
  32363. this._effectiveMaterial.bindView(effect);
  32364. this._effectiveMaterial.bindViewProjection(effect);
  32365. }
  32366. return this;
  32367. };
  32368. /**
  32369. * Registers for this mesh a javascript function called just before the rendering process.
  32370. * This function is passed the current mesh.
  32371. * Return the Mesh.
  32372. */
  32373. Mesh.prototype.registerBeforeRender = function (func) {
  32374. this.onBeforeRenderObservable.add(func);
  32375. return this;
  32376. };
  32377. /**
  32378. * Disposes a previously registered javascript function called before the rendering.
  32379. * This function is passed the current mesh.
  32380. * Returns the Mesh.
  32381. */
  32382. Mesh.prototype.unregisterBeforeRender = function (func) {
  32383. this.onBeforeRenderObservable.removeCallback(func);
  32384. return this;
  32385. };
  32386. /**
  32387. * Registers for this mesh a javascript function called just after the rendering is complete.
  32388. * This function is passed the current mesh.
  32389. * Returns the Mesh.
  32390. */
  32391. Mesh.prototype.registerAfterRender = function (func) {
  32392. this.onAfterRenderObservable.add(func);
  32393. return this;
  32394. };
  32395. /**
  32396. * Disposes a previously registered javascript function called after the rendering.
  32397. * This function is passed the current mesh.
  32398. * Return the Mesh.
  32399. */
  32400. Mesh.prototype.unregisterAfterRender = function (func) {
  32401. this.onAfterRenderObservable.removeCallback(func);
  32402. return this;
  32403. };
  32404. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32405. var scene = this.getScene();
  32406. this._batchCache.mustReturn = false;
  32407. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32408. this._batchCache.visibleInstances[subMeshId] = null;
  32409. if (this._visibleInstances) {
  32410. var currentRenderId = scene.getRenderId();
  32411. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32412. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32413. var selfRenderId = this._renderId;
  32414. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32415. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32416. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32417. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32418. }
  32419. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32420. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32421. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32422. this._batchCache.mustReturn = true;
  32423. return this._batchCache;
  32424. }
  32425. if (currentRenderId !== selfRenderId) {
  32426. this._batchCache.renderSelf[subMeshId] = false;
  32427. }
  32428. }
  32429. this._renderIdForInstances[subMeshId] = currentRenderId;
  32430. }
  32431. return this._batchCache;
  32432. };
  32433. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32434. var visibleInstances = batch.visibleInstances[subMesh._id];
  32435. if (!visibleInstances) {
  32436. return this;
  32437. }
  32438. var matricesCount = visibleInstances.length + 1;
  32439. var bufferSize = matricesCount * 16 * 4;
  32440. var currentInstancesBufferSize = this._instancesBufferSize;
  32441. var instancesBuffer = this._instancesBuffer;
  32442. while (this._instancesBufferSize < bufferSize) {
  32443. this._instancesBufferSize *= 2;
  32444. }
  32445. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32446. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32447. }
  32448. var offset = 0;
  32449. var instancesCount = 0;
  32450. var world = this.getWorldMatrix();
  32451. if (batch.renderSelf[subMesh._id]) {
  32452. world.copyToArray(this._instancesData, offset);
  32453. offset += 16;
  32454. instancesCount++;
  32455. }
  32456. if (visibleInstances) {
  32457. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32458. var instance = visibleInstances[instanceIndex];
  32459. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32460. offset += 16;
  32461. instancesCount++;
  32462. }
  32463. }
  32464. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32465. if (instancesBuffer) {
  32466. instancesBuffer.dispose();
  32467. }
  32468. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32469. this._instancesBuffer = instancesBuffer;
  32470. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32471. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32472. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32473. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32474. }
  32475. else {
  32476. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32477. }
  32478. this._bind(subMesh, effect, fillMode);
  32479. this._draw(subMesh, fillMode, instancesCount);
  32480. engine.unbindInstanceAttributes();
  32481. return this;
  32482. };
  32483. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32484. var scene = this.getScene();
  32485. var engine = scene.getEngine();
  32486. if (hardwareInstancedRendering) {
  32487. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32488. }
  32489. else {
  32490. if (batch.renderSelf[subMesh._id]) {
  32491. // Draw
  32492. if (onBeforeDraw) {
  32493. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32494. }
  32495. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32496. }
  32497. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32498. if (visibleInstancesForSubMesh) {
  32499. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32500. var instance = visibleInstancesForSubMesh[instanceIndex];
  32501. // World
  32502. var world = instance.getWorldMatrix();
  32503. if (onBeforeDraw) {
  32504. onBeforeDraw(true, world, effectiveMaterial);
  32505. }
  32506. // Draw
  32507. this._draw(subMesh, fillMode);
  32508. }
  32509. }
  32510. }
  32511. return this;
  32512. };
  32513. /**
  32514. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  32515. * @param subMesh defines the subMesh to render
  32516. * @param enableAlphaMode defines if alpha mode can be changed
  32517. * @returns the current mesh
  32518. */
  32519. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32520. this._checkOcclusionQuery();
  32521. if (this._isOccluded) {
  32522. return this;
  32523. }
  32524. var scene = this.getScene();
  32525. // Managing instances
  32526. var batch = this._getInstancesRenderList(subMesh._id);
  32527. if (batch.mustReturn) {
  32528. return this;
  32529. }
  32530. // Checking geometry state
  32531. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32532. return this;
  32533. }
  32534. this.onBeforeRenderObservable.notifyObservers(this);
  32535. var engine = scene.getEngine();
  32536. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32537. // Material
  32538. var material = subMesh.getMaterial();
  32539. if (!material) {
  32540. return this;
  32541. }
  32542. this._effectiveMaterial = material;
  32543. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32544. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32545. return this;
  32546. }
  32547. }
  32548. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32549. return this;
  32550. }
  32551. // Alpha mode
  32552. if (enableAlphaMode) {
  32553. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32554. }
  32555. // Outline - step 1
  32556. var savedDepthWrite = engine.getDepthWrite();
  32557. if (this.renderOutline) {
  32558. engine.setDepthWrite(false);
  32559. scene.getOutlineRenderer().render(subMesh, batch);
  32560. engine.setDepthWrite(savedDepthWrite);
  32561. }
  32562. var effect;
  32563. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32564. effect = subMesh.effect;
  32565. }
  32566. else {
  32567. effect = this._effectiveMaterial.getEffect();
  32568. }
  32569. if (!effect) {
  32570. return this;
  32571. }
  32572. var sideOrientation = this.overrideMaterialSideOrientation;
  32573. if (sideOrientation == null) {
  32574. sideOrientation = this._effectiveMaterial.sideOrientation;
  32575. if (this._getWorldMatrixDeterminant() < 0) {
  32576. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32577. }
  32578. }
  32579. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32580. if (this._effectiveMaterial.forceDepthWrite) {
  32581. engine.setDepthWrite(true);
  32582. }
  32583. // Bind
  32584. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32585. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32586. this._bind(subMesh, effect, fillMode);
  32587. }
  32588. var world = this.getWorldMatrix();
  32589. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32590. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32591. }
  32592. else {
  32593. this._effectiveMaterial.bind(world, this);
  32594. }
  32595. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32596. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32597. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32598. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32599. }
  32600. // Draw
  32601. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32602. // Unbind
  32603. this._effectiveMaterial.unbind();
  32604. // Outline - step 2
  32605. if (this.renderOutline && savedDepthWrite) {
  32606. engine.setDepthWrite(true);
  32607. engine.setColorWrite(false);
  32608. scene.getOutlineRenderer().render(subMesh, batch);
  32609. engine.setColorWrite(true);
  32610. }
  32611. // Overlay
  32612. if (this.renderOverlay) {
  32613. var currentMode = engine.getAlphaMode();
  32614. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32615. scene.getOutlineRenderer().render(subMesh, batch, true);
  32616. engine.setAlphaMode(currentMode);
  32617. }
  32618. this.onAfterRenderObservable.notifyObservers(this);
  32619. return this;
  32620. };
  32621. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32622. if (isInstance && effectiveMaterial) {
  32623. effectiveMaterial.bindOnlyWorldMatrix(world);
  32624. }
  32625. };
  32626. /**
  32627. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32628. */
  32629. Mesh.prototype.getEmittedParticleSystems = function () {
  32630. var results = new Array();
  32631. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32632. var particleSystem = this.getScene().particleSystems[index];
  32633. if (particleSystem.emitter === this) {
  32634. results.push(particleSystem);
  32635. }
  32636. }
  32637. return results;
  32638. };
  32639. /**
  32640. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32641. */
  32642. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32643. var results = new Array();
  32644. var descendants = this.getDescendants();
  32645. descendants.push(this);
  32646. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32647. var particleSystem = this.getScene().particleSystems[index];
  32648. var emitter = particleSystem.emitter;
  32649. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32650. results.push(particleSystem);
  32651. }
  32652. }
  32653. return results;
  32654. };
  32655. /**
  32656. * Normalize matrix weights so that all vertices have a total weight set to 1
  32657. */
  32658. Mesh.prototype.cleanMatrixWeights = function () {
  32659. var epsilon = 1e-3;
  32660. var noInfluenceBoneIndex = 0.0;
  32661. if (this.skeleton) {
  32662. noInfluenceBoneIndex = this.skeleton.bones.length;
  32663. }
  32664. else {
  32665. return;
  32666. }
  32667. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32668. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32669. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32670. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32671. var influencers = this.numBoneInfluencers;
  32672. var size = matricesWeights.length;
  32673. for (var i = 0; i < size; i += 4) {
  32674. var weight = 0.0;
  32675. var firstZeroWeight = -1;
  32676. for (var j = 0; j < 4; j++) {
  32677. var w = matricesWeights[i + j];
  32678. weight += w;
  32679. if (w < epsilon && firstZeroWeight < 0) {
  32680. firstZeroWeight = j;
  32681. }
  32682. }
  32683. if (matricesWeightsExtra) {
  32684. for (var j = 0; j < 4; j++) {
  32685. var w = matricesWeightsExtra[i + j];
  32686. weight += w;
  32687. if (w < epsilon && firstZeroWeight < 0) {
  32688. firstZeroWeight = j + 4;
  32689. }
  32690. }
  32691. }
  32692. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32693. firstZeroWeight = influencers - 1;
  32694. }
  32695. if (weight > epsilon) {
  32696. var mweight = 1.0 / weight;
  32697. for (var j = 0; j < 4; j++) {
  32698. matricesWeights[i + j] *= mweight;
  32699. }
  32700. if (matricesWeightsExtra) {
  32701. for (var j = 0; j < 4; j++) {
  32702. matricesWeightsExtra[i + j] *= mweight;
  32703. }
  32704. }
  32705. }
  32706. else {
  32707. if (firstZeroWeight >= 4) {
  32708. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32709. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32710. }
  32711. else {
  32712. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32713. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32714. }
  32715. }
  32716. }
  32717. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32718. if (matricesIndicesExtra) {
  32719. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32720. }
  32721. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32722. if (matricesWeightsExtra) {
  32723. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32724. }
  32725. };
  32726. Mesh.prototype._checkDelayState = function () {
  32727. var scene = this.getScene();
  32728. if (this._geometry) {
  32729. this._geometry.load(scene);
  32730. }
  32731. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32732. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32733. this._queueLoad(scene);
  32734. }
  32735. return this;
  32736. };
  32737. Mesh.prototype._queueLoad = function (scene) {
  32738. var _this = this;
  32739. scene._addPendingData(this);
  32740. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32741. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32742. if (data instanceof ArrayBuffer) {
  32743. _this._delayLoadingFunction(data, _this);
  32744. }
  32745. else {
  32746. _this._delayLoadingFunction(JSON.parse(data), _this);
  32747. }
  32748. _this.instances.forEach(function (instance) {
  32749. instance._syncSubMeshes();
  32750. });
  32751. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32752. scene._removePendingData(_this);
  32753. }, function () { }, scene.database, getBinaryData);
  32754. return this;
  32755. };
  32756. /**
  32757. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32758. */
  32759. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32760. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32761. return false;
  32762. }
  32763. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32764. return false;
  32765. }
  32766. this._checkDelayState();
  32767. return true;
  32768. };
  32769. /**
  32770. * Sets the mesh material by the material or multiMaterial `id` property.
  32771. * The material `id` is a string identifying the material or the multiMaterial.
  32772. * This method returns the Mesh.
  32773. */
  32774. Mesh.prototype.setMaterialByID = function (id) {
  32775. var materials = this.getScene().materials;
  32776. var index;
  32777. for (index = materials.length - 1; index > -1; index--) {
  32778. if (materials[index].id === id) {
  32779. this.material = materials[index];
  32780. return this;
  32781. }
  32782. }
  32783. // Multi
  32784. var multiMaterials = this.getScene().multiMaterials;
  32785. for (index = multiMaterials.length - 1; index > -1; index--) {
  32786. if (multiMaterials[index].id === id) {
  32787. this.material = multiMaterials[index];
  32788. return this;
  32789. }
  32790. }
  32791. return this;
  32792. };
  32793. /**
  32794. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32795. */
  32796. Mesh.prototype.getAnimatables = function () {
  32797. var results = new Array();
  32798. if (this.material) {
  32799. results.push(this.material);
  32800. }
  32801. if (this.skeleton) {
  32802. results.push(this.skeleton);
  32803. }
  32804. return results;
  32805. };
  32806. /**
  32807. * Modifies the mesh geometry according to the passed transformation matrix.
  32808. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32809. * The mesh normals are modified accordingly the same transformation.
  32810. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32811. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32812. * Returns the Mesh.
  32813. */
  32814. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32815. // Position
  32816. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32817. return this;
  32818. }
  32819. var submeshes = this.subMeshes.splice(0);
  32820. this._resetPointsArrayCache();
  32821. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32822. var temp = new Array();
  32823. var index;
  32824. for (index = 0; index < data.length; index += 3) {
  32825. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32826. }
  32827. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32828. // Normals
  32829. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32830. return this;
  32831. }
  32832. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32833. temp = [];
  32834. for (index = 0; index < data.length; index += 3) {
  32835. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32836. }
  32837. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32838. // flip faces?
  32839. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32840. this.flipFaces();
  32841. }
  32842. // Restore submeshes
  32843. this.releaseSubMeshes();
  32844. this.subMeshes = submeshes;
  32845. return this;
  32846. };
  32847. /**
  32848. * Modifies the mesh geometry according to its own current World Matrix.
  32849. * The mesh World Matrix is then reset.
  32850. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32851. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32852. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32853. * Returns the Mesh.
  32854. */
  32855. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32856. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32857. this.scaling.copyFromFloats(1, 1, 1);
  32858. this.position.copyFromFloats(0, 0, 0);
  32859. this.rotation.copyFromFloats(0, 0, 0);
  32860. //only if quaternion is already set
  32861. if (this.rotationQuaternion) {
  32862. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32863. }
  32864. this._worldMatrix = BABYLON.Matrix.Identity();
  32865. return this;
  32866. };
  32867. Object.defineProperty(Mesh.prototype, "_positions", {
  32868. // Cache
  32869. get: function () {
  32870. if (this._geometry) {
  32871. return this._geometry._positions;
  32872. }
  32873. return null;
  32874. },
  32875. enumerable: true,
  32876. configurable: true
  32877. });
  32878. Mesh.prototype._resetPointsArrayCache = function () {
  32879. if (this._geometry) {
  32880. this._geometry._resetPointsArrayCache();
  32881. }
  32882. return this;
  32883. };
  32884. Mesh.prototype._generatePointsArray = function () {
  32885. if (this._geometry) {
  32886. return this._geometry._generatePointsArray();
  32887. }
  32888. return false;
  32889. };
  32890. /**
  32891. * Returns a new Mesh object generated from the current mesh properties.
  32892. * This method must not get confused with createInstance().
  32893. * The parameter `name` is a string, the name given to the new mesh.
  32894. * The optional parameter `newParent` can be any Node object (default `null`).
  32895. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32896. * 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.
  32897. */
  32898. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32899. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32900. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32901. };
  32902. /**
  32903. * Releases resources associated with this mesh.
  32904. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32905. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32906. */
  32907. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32908. var _this = this;
  32909. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32910. this.morphTargetManager = null;
  32911. if (this._geometry) {
  32912. this._geometry.releaseForMesh(this, true);
  32913. }
  32914. // Sources
  32915. var meshes = this.getScene().meshes;
  32916. meshes.forEach(function (abstractMesh) {
  32917. var mesh = abstractMesh;
  32918. if (mesh._source && mesh._source === _this) {
  32919. mesh._source = null;
  32920. }
  32921. });
  32922. this._source = null;
  32923. // Instances
  32924. if (this._instancesBuffer) {
  32925. this._instancesBuffer.dispose();
  32926. this._instancesBuffer = null;
  32927. }
  32928. while (this.instances.length) {
  32929. this.instances[0].dispose();
  32930. }
  32931. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32932. };
  32933. /**
  32934. * Modifies the mesh geometry according to a displacement map.
  32935. * 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.
  32936. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32937. * This method returns nothing.
  32938. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32939. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32940. * 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.
  32941. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32942. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32943. *
  32944. * Returns the Mesh.
  32945. */
  32946. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32947. var _this = this;
  32948. var scene = this.getScene();
  32949. var onload = function (img) {
  32950. // Getting height map data
  32951. var canvas = document.createElement("canvas");
  32952. var context = canvas.getContext("2d");
  32953. var heightMapWidth = img.width;
  32954. var heightMapHeight = img.height;
  32955. canvas.width = heightMapWidth;
  32956. canvas.height = heightMapHeight;
  32957. context.drawImage(img, 0, 0);
  32958. // Create VertexData from map data
  32959. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32960. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32961. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32962. //execute success callback, if set
  32963. if (onSuccess) {
  32964. onSuccess(_this);
  32965. }
  32966. };
  32967. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32968. return this;
  32969. };
  32970. /**
  32971. * Modifies the mesh geometry according to a displacementMap buffer.
  32972. * 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.
  32973. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32974. * This method returns nothing.
  32975. * 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.
  32976. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32977. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32978. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32979. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32980. *
  32981. * Returns the Mesh.
  32982. */
  32983. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32984. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32985. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32986. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32987. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32988. return this;
  32989. }
  32990. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32991. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32992. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32993. var position = BABYLON.Vector3.Zero();
  32994. var normal = BABYLON.Vector3.Zero();
  32995. var uv = BABYLON.Vector2.Zero();
  32996. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32997. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32998. for (var index = 0; index < positions.length; index += 3) {
  32999. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33000. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33001. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33002. // Compute height
  33003. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33004. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33005. var pos = (u + v * heightMapWidth) * 4;
  33006. var r = buffer[pos] / 255.0;
  33007. var g = buffer[pos + 1] / 255.0;
  33008. var b = buffer[pos + 2] / 255.0;
  33009. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33010. normal.normalize();
  33011. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33012. position = position.add(normal);
  33013. position.toArray(positions, index);
  33014. }
  33015. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33016. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33017. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33018. return this;
  33019. };
  33020. /**
  33021. * Modify the mesh to get a flat shading rendering.
  33022. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33023. * This method returns the Mesh.
  33024. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33025. */
  33026. Mesh.prototype.convertToFlatShadedMesh = function () {
  33027. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33028. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33029. var kinds = this.getVerticesDataKinds();
  33030. var vbs = {};
  33031. var data = {};
  33032. var newdata = {};
  33033. var updatableNormals = false;
  33034. var kindIndex;
  33035. var kind;
  33036. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33037. kind = kinds[kindIndex];
  33038. var vertexBuffer = this.getVertexBuffer(kind);
  33039. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33040. updatableNormals = vertexBuffer.isUpdatable();
  33041. kinds.splice(kindIndex, 1);
  33042. kindIndex--;
  33043. continue;
  33044. }
  33045. vbs[kind] = vertexBuffer;
  33046. data[kind] = vbs[kind].getData();
  33047. newdata[kind] = [];
  33048. }
  33049. // Save previous submeshes
  33050. var previousSubmeshes = this.subMeshes.slice(0);
  33051. var indices = this.getIndices();
  33052. var totalIndices = this.getTotalIndices();
  33053. // Generating unique vertices per face
  33054. var index;
  33055. for (index = 0; index < totalIndices; index++) {
  33056. var vertexIndex = indices[index];
  33057. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33058. kind = kinds[kindIndex];
  33059. var stride = vbs[kind].getStrideSize();
  33060. for (var offset = 0; offset < stride; offset++) {
  33061. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33062. }
  33063. }
  33064. }
  33065. // Updating faces & normal
  33066. var normals = [];
  33067. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33068. for (index = 0; index < totalIndices; index += 3) {
  33069. indices[index] = index;
  33070. indices[index + 1] = index + 1;
  33071. indices[index + 2] = index + 2;
  33072. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33073. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33074. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33075. var p1p2 = p1.subtract(p2);
  33076. var p3p2 = p3.subtract(p2);
  33077. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33078. // Store same normals for every vertex
  33079. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33080. normals.push(normal.x);
  33081. normals.push(normal.y);
  33082. normals.push(normal.z);
  33083. }
  33084. }
  33085. this.setIndices(indices);
  33086. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33087. // Updating vertex buffers
  33088. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33089. kind = kinds[kindIndex];
  33090. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33091. }
  33092. // Updating submeshes
  33093. this.releaseSubMeshes();
  33094. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33095. var previousOne = previousSubmeshes[submeshIndex];
  33096. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33097. }
  33098. this.synchronizeInstances();
  33099. return this;
  33100. };
  33101. /**
  33102. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33103. * In other words, more vertices, no more indices and a single bigger VBO.
  33104. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33105. * Returns the Mesh.
  33106. */
  33107. Mesh.prototype.convertToUnIndexedMesh = function () {
  33108. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33109. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33110. var kinds = this.getVerticesDataKinds();
  33111. var vbs = {};
  33112. var data = {};
  33113. var newdata = {};
  33114. var kindIndex;
  33115. var kind;
  33116. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33117. kind = kinds[kindIndex];
  33118. var vertexBuffer = this.getVertexBuffer(kind);
  33119. vbs[kind] = vertexBuffer;
  33120. data[kind] = vbs[kind].getData();
  33121. newdata[kind] = [];
  33122. }
  33123. // Save previous submeshes
  33124. var previousSubmeshes = this.subMeshes.slice(0);
  33125. var indices = this.getIndices();
  33126. var totalIndices = this.getTotalIndices();
  33127. // Generating unique vertices per face
  33128. var index;
  33129. for (index = 0; index < totalIndices; index++) {
  33130. var vertexIndex = indices[index];
  33131. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33132. kind = kinds[kindIndex];
  33133. var stride = vbs[kind].getStrideSize();
  33134. for (var offset = 0; offset < stride; offset++) {
  33135. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33136. }
  33137. }
  33138. }
  33139. // Updating indices
  33140. for (index = 0; index < totalIndices; index += 3) {
  33141. indices[index] = index;
  33142. indices[index + 1] = index + 1;
  33143. indices[index + 2] = index + 2;
  33144. }
  33145. this.setIndices(indices);
  33146. // Updating vertex buffers
  33147. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33148. kind = kinds[kindIndex];
  33149. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33150. }
  33151. // Updating submeshes
  33152. this.releaseSubMeshes();
  33153. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33154. var previousOne = previousSubmeshes[submeshIndex];
  33155. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33156. }
  33157. this._unIndexed = true;
  33158. this.synchronizeInstances();
  33159. return this;
  33160. };
  33161. /**
  33162. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33163. * This method returns the Mesh.
  33164. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33165. */
  33166. Mesh.prototype.flipFaces = function (flipNormals) {
  33167. if (flipNormals === void 0) { flipNormals = false; }
  33168. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33169. var i;
  33170. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33171. for (i = 0; i < vertex_data.normals.length; i++) {
  33172. vertex_data.normals[i] *= -1;
  33173. }
  33174. }
  33175. if (vertex_data.indices) {
  33176. var temp;
  33177. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33178. // reassign indices
  33179. temp = vertex_data.indices[i + 1];
  33180. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33181. vertex_data.indices[i + 2] = temp;
  33182. }
  33183. }
  33184. vertex_data.applyToMesh(this);
  33185. return this;
  33186. };
  33187. // Instances
  33188. /**
  33189. * Creates a new InstancedMesh object from the mesh model.
  33190. * An instance shares the same properties and the same material than its model.
  33191. * Only these properties of each instance can then be set individually :
  33192. * - position
  33193. * - rotation
  33194. * - rotationQuaternion
  33195. * - setPivotMatrix
  33196. * - scaling
  33197. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33198. * Warning : this method is not supported for Line mesh and LineSystem
  33199. */
  33200. Mesh.prototype.createInstance = function (name) {
  33201. return new BABYLON.InstancedMesh(name, this);
  33202. };
  33203. /**
  33204. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33205. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33206. * This method returns the Mesh.
  33207. */
  33208. Mesh.prototype.synchronizeInstances = function () {
  33209. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33210. var instance = this.instances[instanceIndex];
  33211. instance._syncSubMeshes();
  33212. }
  33213. return this;
  33214. };
  33215. /**
  33216. * Simplify the mesh according to the given array of settings.
  33217. * Function will return immediately and will simplify async. It returns the Mesh.
  33218. * @param settings a collection of simplification settings.
  33219. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33220. * @param type the type of simplification to run.
  33221. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33222. */
  33223. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33224. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33225. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33226. this.getScene().simplificationQueue.addTask({
  33227. settings: settings,
  33228. parallelProcessing: parallelProcessing,
  33229. mesh: this,
  33230. simplificationType: simplificationType,
  33231. successCallback: successCallback
  33232. });
  33233. return this;
  33234. };
  33235. /**
  33236. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33237. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33238. * This should be used together with the simplification to avoid disappearing triangles.
  33239. * Returns the Mesh.
  33240. * @param successCallback an optional success callback to be called after the optimization finished.
  33241. */
  33242. Mesh.prototype.optimizeIndices = function (successCallback) {
  33243. var _this = this;
  33244. var indices = this.getIndices();
  33245. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33246. if (!positions || !indices) {
  33247. return this;
  33248. }
  33249. var vectorPositions = new Array();
  33250. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33251. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33252. }
  33253. var dupes = new Array();
  33254. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33255. var realPos = vectorPositions.length - 1 - iteration;
  33256. var testedPosition = vectorPositions[realPos];
  33257. for (var j = 0; j < realPos; ++j) {
  33258. var againstPosition = vectorPositions[j];
  33259. if (testedPosition.equals(againstPosition)) {
  33260. dupes[realPos] = j;
  33261. break;
  33262. }
  33263. }
  33264. }, function () {
  33265. for (var i = 0; i < indices.length; ++i) {
  33266. indices[i] = dupes[indices[i]] || indices[i];
  33267. }
  33268. //indices are now reordered
  33269. var originalSubMeshes = _this.subMeshes.slice(0);
  33270. _this.setIndices(indices);
  33271. _this.subMeshes = originalSubMeshes;
  33272. if (successCallback) {
  33273. successCallback(_this);
  33274. }
  33275. });
  33276. return this;
  33277. };
  33278. Mesh.prototype.serialize = function (serializationObject) {
  33279. serializationObject.name = this.name;
  33280. serializationObject.id = this.id;
  33281. serializationObject.type = this.getClassName();
  33282. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33283. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33284. }
  33285. serializationObject.position = this.position.asArray();
  33286. if (this.rotationQuaternion) {
  33287. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33288. }
  33289. else if (this.rotation) {
  33290. serializationObject.rotation = this.rotation.asArray();
  33291. }
  33292. serializationObject.scaling = this.scaling.asArray();
  33293. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33294. serializationObject.isEnabled = this.isEnabled(false);
  33295. serializationObject.isVisible = this.isVisible;
  33296. serializationObject.infiniteDistance = this.infiniteDistance;
  33297. serializationObject.pickable = this.isPickable;
  33298. serializationObject.receiveShadows = this.receiveShadows;
  33299. serializationObject.billboardMode = this.billboardMode;
  33300. serializationObject.visibility = this.visibility;
  33301. serializationObject.checkCollisions = this.checkCollisions;
  33302. serializationObject.isBlocker = this.isBlocker;
  33303. // Parent
  33304. if (this.parent) {
  33305. serializationObject.parentId = this.parent.id;
  33306. }
  33307. // Geometry
  33308. serializationObject.isUnIndexed = this.isUnIndexed;
  33309. var geometry = this._geometry;
  33310. if (geometry) {
  33311. var geometryId = geometry.id;
  33312. serializationObject.geometryId = geometryId;
  33313. // SubMeshes
  33314. serializationObject.subMeshes = [];
  33315. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33316. var subMesh = this.subMeshes[subIndex];
  33317. serializationObject.subMeshes.push({
  33318. materialIndex: subMesh.materialIndex,
  33319. verticesStart: subMesh.verticesStart,
  33320. verticesCount: subMesh.verticesCount,
  33321. indexStart: subMesh.indexStart,
  33322. indexCount: subMesh.indexCount
  33323. });
  33324. }
  33325. }
  33326. // Material
  33327. if (this.material) {
  33328. serializationObject.materialId = this.material.id;
  33329. }
  33330. else {
  33331. this.material = null;
  33332. }
  33333. // Morph targets
  33334. if (this.morphTargetManager) {
  33335. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33336. }
  33337. // Skeleton
  33338. if (this.skeleton) {
  33339. serializationObject.skeletonId = this.skeleton.id;
  33340. }
  33341. // Physics
  33342. //TODO implement correct serialization for physics impostors.
  33343. var impostor = this.getPhysicsImpostor();
  33344. if (impostor) {
  33345. serializationObject.physicsMass = impostor.getParam("mass");
  33346. serializationObject.physicsFriction = impostor.getParam("friction");
  33347. serializationObject.physicsRestitution = impostor.getParam("mass");
  33348. serializationObject.physicsImpostor = impostor.type;
  33349. }
  33350. // Metadata
  33351. if (this.metadata) {
  33352. serializationObject.metadata = this.metadata;
  33353. }
  33354. // Instances
  33355. serializationObject.instances = [];
  33356. for (var index = 0; index < this.instances.length; index++) {
  33357. var instance = this.instances[index];
  33358. var serializationInstance = {
  33359. name: instance.name,
  33360. id: instance.id,
  33361. position: instance.position.asArray(),
  33362. scaling: instance.scaling.asArray()
  33363. };
  33364. if (instance.rotationQuaternion) {
  33365. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33366. }
  33367. else if (instance.rotation) {
  33368. serializationInstance.rotation = instance.rotation.asArray();
  33369. }
  33370. serializationObject.instances.push(serializationInstance);
  33371. // Animations
  33372. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33373. serializationInstance.ranges = instance.serializeAnimationRanges();
  33374. }
  33375. //
  33376. // Animations
  33377. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33378. serializationObject.ranges = this.serializeAnimationRanges();
  33379. // Layer mask
  33380. serializationObject.layerMask = this.layerMask;
  33381. // Alpha
  33382. serializationObject.alphaIndex = this.alphaIndex;
  33383. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33384. // Overlay
  33385. serializationObject.overlayAlpha = this.overlayAlpha;
  33386. serializationObject.overlayColor = this.overlayColor.asArray();
  33387. serializationObject.renderOverlay = this.renderOverlay;
  33388. // Fog
  33389. serializationObject.applyFog = this.applyFog;
  33390. // Action Manager
  33391. if (this.actionManager) {
  33392. serializationObject.actions = this.actionManager.serialize(this.name);
  33393. }
  33394. };
  33395. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33396. if (!this.geometry) {
  33397. return;
  33398. }
  33399. this._markSubMeshesAsAttributesDirty();
  33400. var morphTargetManager = this._morphTargetManager;
  33401. if (morphTargetManager && morphTargetManager.vertexCount) {
  33402. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33403. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33404. this.morphTargetManager = null;
  33405. return;
  33406. }
  33407. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33408. var morphTarget = morphTargetManager.getActiveTarget(index);
  33409. var positions = morphTarget.getPositions();
  33410. if (!positions) {
  33411. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33412. return;
  33413. }
  33414. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33415. var normals = morphTarget.getNormals();
  33416. if (normals) {
  33417. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33418. }
  33419. var tangents = morphTarget.getTangents();
  33420. if (tangents) {
  33421. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33422. }
  33423. }
  33424. }
  33425. else {
  33426. var index = 0;
  33427. // Positions
  33428. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33429. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33430. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33431. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33432. }
  33433. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33434. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33435. }
  33436. index++;
  33437. }
  33438. }
  33439. };
  33440. // Statics
  33441. /**
  33442. * Returns a new Mesh object parsed from the source provided.
  33443. * The parameter `parsedMesh` is the source.
  33444. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33445. */
  33446. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33447. var mesh;
  33448. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33449. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33450. }
  33451. else {
  33452. mesh = new Mesh(parsedMesh.name, scene);
  33453. }
  33454. mesh.id = parsedMesh.id;
  33455. if (BABYLON.Tags) {
  33456. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33457. }
  33458. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33459. if (parsedMesh.metadata !== undefined) {
  33460. mesh.metadata = parsedMesh.metadata;
  33461. }
  33462. if (parsedMesh.rotationQuaternion) {
  33463. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33464. }
  33465. else if (parsedMesh.rotation) {
  33466. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33467. }
  33468. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33469. if (parsedMesh.localMatrix) {
  33470. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33471. }
  33472. else if (parsedMesh.pivotMatrix) {
  33473. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33474. }
  33475. mesh.setEnabled(parsedMesh.isEnabled);
  33476. mesh.isVisible = parsedMesh.isVisible;
  33477. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33478. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33479. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33480. if (parsedMesh.applyFog !== undefined) {
  33481. mesh.applyFog = parsedMesh.applyFog;
  33482. }
  33483. if (parsedMesh.pickable !== undefined) {
  33484. mesh.isPickable = parsedMesh.pickable;
  33485. }
  33486. if (parsedMesh.alphaIndex !== undefined) {
  33487. mesh.alphaIndex = parsedMesh.alphaIndex;
  33488. }
  33489. mesh.receiveShadows = parsedMesh.receiveShadows;
  33490. mesh.billboardMode = parsedMesh.billboardMode;
  33491. if (parsedMesh.visibility !== undefined) {
  33492. mesh.visibility = parsedMesh.visibility;
  33493. }
  33494. mesh.checkCollisions = parsedMesh.checkCollisions;
  33495. if (parsedMesh.isBlocker !== undefined) {
  33496. mesh.isBlocker = parsedMesh.isBlocker;
  33497. }
  33498. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33499. // freezeWorldMatrix
  33500. if (parsedMesh.freezeWorldMatrix) {
  33501. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33502. }
  33503. // Parent
  33504. if (parsedMesh.parentId) {
  33505. mesh._waitingParentId = parsedMesh.parentId;
  33506. }
  33507. // Actions
  33508. if (parsedMesh.actions !== undefined) {
  33509. mesh._waitingActions = parsedMesh.actions;
  33510. }
  33511. // Overlay
  33512. if (parsedMesh.overlayAlpha !== undefined) {
  33513. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33514. }
  33515. if (parsedMesh.overlayColor !== undefined) {
  33516. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33517. }
  33518. if (parsedMesh.renderOverlay !== undefined) {
  33519. mesh.renderOverlay = parsedMesh.renderOverlay;
  33520. }
  33521. // Geometry
  33522. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33523. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33524. if (parsedMesh.delayLoadingFile) {
  33525. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33526. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33527. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33528. if (parsedMesh._binaryInfo) {
  33529. mesh._binaryInfo = parsedMesh._binaryInfo;
  33530. }
  33531. mesh._delayInfo = [];
  33532. if (parsedMesh.hasUVs) {
  33533. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33534. }
  33535. if (parsedMesh.hasUVs2) {
  33536. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33537. }
  33538. if (parsedMesh.hasUVs3) {
  33539. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33540. }
  33541. if (parsedMesh.hasUVs4) {
  33542. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33543. }
  33544. if (parsedMesh.hasUVs5) {
  33545. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33546. }
  33547. if (parsedMesh.hasUVs6) {
  33548. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33549. }
  33550. if (parsedMesh.hasColors) {
  33551. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33552. }
  33553. if (parsedMesh.hasMatricesIndices) {
  33554. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33555. }
  33556. if (parsedMesh.hasMatricesWeights) {
  33557. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33558. }
  33559. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33560. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33561. mesh._checkDelayState();
  33562. }
  33563. }
  33564. else {
  33565. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33566. }
  33567. // Material
  33568. if (parsedMesh.materialId) {
  33569. mesh.setMaterialByID(parsedMesh.materialId);
  33570. }
  33571. else {
  33572. mesh.material = null;
  33573. }
  33574. // Morph targets
  33575. if (parsedMesh.morphTargetManagerId > -1) {
  33576. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33577. }
  33578. // Skeleton
  33579. if (parsedMesh.skeletonId > -1) {
  33580. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33581. if (parsedMesh.numBoneInfluencers) {
  33582. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33583. }
  33584. }
  33585. // Animations
  33586. if (parsedMesh.animations) {
  33587. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33588. var parsedAnimation = parsedMesh.animations[animationIndex];
  33589. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33590. }
  33591. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33592. }
  33593. if (parsedMesh.autoAnimate) {
  33594. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33595. }
  33596. // Layer Mask
  33597. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33598. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33599. }
  33600. else {
  33601. mesh.layerMask = 0x0FFFFFFF;
  33602. }
  33603. // Physics
  33604. if (parsedMesh.physicsImpostor) {
  33605. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33606. mass: parsedMesh.physicsMass,
  33607. friction: parsedMesh.physicsFriction,
  33608. restitution: parsedMesh.physicsRestitution
  33609. }, scene);
  33610. }
  33611. // Instances
  33612. if (parsedMesh.instances) {
  33613. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33614. var parsedInstance = parsedMesh.instances[index];
  33615. var instance = mesh.createInstance(parsedInstance.name);
  33616. if (parsedInstance.id) {
  33617. instance.id = parsedInstance.id;
  33618. }
  33619. if (BABYLON.Tags) {
  33620. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33621. }
  33622. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33623. if (parsedInstance.parentId) {
  33624. instance._waitingParentId = parsedInstance.parentId;
  33625. }
  33626. if (parsedInstance.rotationQuaternion) {
  33627. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33628. }
  33629. else if (parsedInstance.rotation) {
  33630. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33631. }
  33632. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33633. instance.checkCollisions = mesh.checkCollisions;
  33634. if (parsedMesh.animations) {
  33635. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33636. parsedAnimation = parsedMesh.animations[animationIndex];
  33637. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33638. }
  33639. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33640. if (parsedMesh.autoAnimate) {
  33641. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33642. }
  33643. }
  33644. }
  33645. }
  33646. return mesh;
  33647. };
  33648. /**
  33649. * Creates a ribbon mesh.
  33650. * Please consider using the same method from the MeshBuilder class instead.
  33651. * 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.
  33652. *
  33653. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33654. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33655. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33656. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33657. * 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.
  33658. * 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.
  33659. * 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
  33660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33661. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33663. */
  33664. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33665. if (closeArray === void 0) { closeArray = false; }
  33666. if (updatable === void 0) { updatable = false; }
  33667. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33668. pathArray: pathArray,
  33669. closeArray: closeArray,
  33670. closePath: closePath,
  33671. offset: offset,
  33672. updatable: updatable,
  33673. sideOrientation: sideOrientation,
  33674. instance: instance
  33675. }, scene);
  33676. };
  33677. /**
  33678. * Creates a plane polygonal mesh. By default, this is a disc.
  33679. * Please consider using the same method from the MeshBuilder class instead.
  33680. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33681. * 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.
  33682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33683. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33684. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33685. */
  33686. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33687. if (scene === void 0) { scene = null; }
  33688. var options = {
  33689. radius: radius,
  33690. tessellation: tessellation,
  33691. sideOrientation: sideOrientation,
  33692. updatable: updatable
  33693. };
  33694. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33695. };
  33696. /**
  33697. * Creates a box mesh.
  33698. * Please consider using the same method from the MeshBuilder class instead.
  33699. * The parameter `size` sets the size (float) of each box side (default 1).
  33700. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33701. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33703. */
  33704. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33705. if (scene === void 0) { scene = null; }
  33706. var options = {
  33707. size: size,
  33708. sideOrientation: sideOrientation,
  33709. updatable: updatable
  33710. };
  33711. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33712. };
  33713. /**
  33714. * Creates a sphere mesh.
  33715. * Please consider using the same method from the MeshBuilder class instead.
  33716. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33717. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33718. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33719. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33721. */
  33722. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33723. var options = {
  33724. segments: segments,
  33725. diameterX: diameter,
  33726. diameterY: diameter,
  33727. diameterZ: diameter,
  33728. sideOrientation: sideOrientation,
  33729. updatable: updatable
  33730. };
  33731. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33732. };
  33733. /**
  33734. * Creates a cylinder or a cone mesh.
  33735. * Please consider using the same method from the MeshBuilder class instead.
  33736. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33737. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33738. * 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.
  33739. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33740. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33742. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33744. */
  33745. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33746. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33747. if (scene !== undefined) {
  33748. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33749. updatable = scene;
  33750. }
  33751. scene = subdivisions;
  33752. subdivisions = 1;
  33753. }
  33754. var options = {
  33755. height: height,
  33756. diameterTop: diameterTop,
  33757. diameterBottom: diameterBottom,
  33758. tessellation: tessellation,
  33759. subdivisions: subdivisions,
  33760. sideOrientation: sideOrientation,
  33761. updatable: updatable
  33762. };
  33763. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33764. };
  33765. // Torus (Code from SharpDX.org)
  33766. /**
  33767. * Creates a torus mesh.
  33768. * Please consider using the same method from the MeshBuilder class instead.
  33769. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33770. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33771. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33772. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33773. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33775. */
  33776. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33777. var options = {
  33778. diameter: diameter,
  33779. thickness: thickness,
  33780. tessellation: tessellation,
  33781. sideOrientation: sideOrientation,
  33782. updatable: updatable
  33783. };
  33784. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33785. };
  33786. /**
  33787. * Creates a torus knot mesh.
  33788. * Please consider using the same method from the MeshBuilder class instead.
  33789. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33790. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33791. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33792. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33793. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33794. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33796. */
  33797. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33798. var options = {
  33799. radius: radius,
  33800. tube: tube,
  33801. radialSegments: radialSegments,
  33802. tubularSegments: tubularSegments,
  33803. p: p,
  33804. q: q,
  33805. sideOrientation: sideOrientation,
  33806. updatable: updatable
  33807. };
  33808. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33809. };
  33810. /**
  33811. * Creates a line mesh.
  33812. * Please consider using the same method from the MeshBuilder class instead.
  33813. * 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.
  33814. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33815. * The parameter `points` is an array successive Vector3.
  33816. * 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
  33817. * When updating an instance, remember that only point positions can change, not the number of points.
  33818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33819. */
  33820. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33821. if (scene === void 0) { scene = null; }
  33822. if (updatable === void 0) { updatable = false; }
  33823. if (instance === void 0) { instance = null; }
  33824. var options = {
  33825. points: points,
  33826. updatable: updatable,
  33827. instance: instance
  33828. };
  33829. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33830. };
  33831. /**
  33832. * Creates a dashed line mesh.
  33833. * Please consider using the same method from the MeshBuilder class instead.
  33834. * 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.
  33835. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33836. * The parameter `points` is an array successive Vector3.
  33837. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33838. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33839. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33840. * 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
  33841. * When updating an instance, remember that only point positions can change, not the number of points.
  33842. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33843. */
  33844. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33845. if (scene === void 0) { scene = null; }
  33846. var options = {
  33847. points: points,
  33848. dashSize: dashSize,
  33849. gapSize: gapSize,
  33850. dashNb: dashNb,
  33851. updatable: updatable,
  33852. instance: instance
  33853. };
  33854. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33855. };
  33856. /**
  33857. * Creates a polygon mesh.
  33858. * Please consider using the same method from the MeshBuilder class instead.
  33859. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33860. * 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.
  33861. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33863. * Remember you can only change the shape positions, not their number when updating a polygon.
  33864. */
  33865. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33866. var options = {
  33867. shape: shape,
  33868. holes: holes,
  33869. updatable: updatable,
  33870. sideOrientation: sideOrientation
  33871. };
  33872. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33873. };
  33874. /**
  33875. * Creates an extruded polygon mesh, with depth in the Y direction.
  33876. * Please consider using the same method from the MeshBuilder class instead.
  33877. */
  33878. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33879. var options = {
  33880. shape: shape,
  33881. holes: holes,
  33882. depth: depth,
  33883. updatable: updatable,
  33884. sideOrientation: sideOrientation
  33885. };
  33886. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33887. };
  33888. /**
  33889. * Creates an extruded shape mesh.
  33890. * 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.
  33891. * Please consider using the same method from the MeshBuilder class instead.
  33892. *
  33893. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33894. * 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
  33895. * extruded along the Z axis.
  33896. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33897. * 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.
  33898. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33899. * 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
  33900. * 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
  33901. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33902. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33903. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33905. */
  33906. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33907. if (scene === void 0) { scene = null; }
  33908. var options = {
  33909. shape: shape,
  33910. path: path,
  33911. scale: scale,
  33912. rotation: rotation,
  33913. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33914. sideOrientation: sideOrientation,
  33915. instance: instance,
  33916. updatable: updatable
  33917. };
  33918. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33919. };
  33920. /**
  33921. * Creates an custom extruded shape mesh.
  33922. * 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.
  33923. * Please consider using the same method from the MeshBuilder class instead.
  33924. *
  33925. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33926. * 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
  33927. * extruded along the Z axis.
  33928. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33929. * 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
  33930. * and the distance of this point from the begining of the path :
  33931. * ```javascript
  33932. * var rotationFunction = function(i, distance) {
  33933. * // do things
  33934. * return rotationValue; }
  33935. * ```
  33936. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33937. * 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
  33938. * and the distance of this point from the begining of the path :
  33939. * ```javascript
  33940. * var scaleFunction = function(i, distance) {
  33941. * // do things
  33942. * return scaleValue;}
  33943. * ```
  33944. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33945. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33946. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33947. * 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
  33948. * 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
  33949. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33951. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33953. */
  33954. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33955. var options = {
  33956. shape: shape,
  33957. path: path,
  33958. scaleFunction: scaleFunction,
  33959. rotationFunction: rotationFunction,
  33960. ribbonCloseArray: ribbonCloseArray,
  33961. ribbonClosePath: ribbonClosePath,
  33962. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33963. sideOrientation: sideOrientation,
  33964. instance: instance,
  33965. updatable: updatable
  33966. };
  33967. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33968. };
  33969. /**
  33970. * Creates lathe mesh.
  33971. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33972. * Please consider using the same method from the MeshBuilder class instead.
  33973. * 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
  33974. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33975. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33976. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33977. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33978. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33979. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33980. */
  33981. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33982. var options = {
  33983. shape: shape,
  33984. radius: radius,
  33985. tessellation: tessellation,
  33986. sideOrientation: sideOrientation,
  33987. updatable: updatable
  33988. };
  33989. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33990. };
  33991. /**
  33992. * Creates a plane mesh.
  33993. * Please consider using the same method from the MeshBuilder class instead.
  33994. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33995. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33996. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33998. */
  33999. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34000. var options = {
  34001. size: size,
  34002. width: size,
  34003. height: size,
  34004. sideOrientation: sideOrientation,
  34005. updatable: updatable
  34006. };
  34007. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34008. };
  34009. /**
  34010. * Creates a ground mesh.
  34011. * Please consider using the same method from the MeshBuilder class instead.
  34012. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34013. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34015. */
  34016. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34017. var options = {
  34018. width: width,
  34019. height: height,
  34020. subdivisions: subdivisions,
  34021. updatable: updatable
  34022. };
  34023. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34024. };
  34025. /**
  34026. * Creates a tiled ground mesh.
  34027. * Please consider using the same method from the MeshBuilder class instead.
  34028. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34029. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34030. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34031. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34032. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34033. * numbers of subdivisions on the ground width and height of each tile.
  34034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34035. */
  34036. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34037. var options = {
  34038. xmin: xmin,
  34039. zmin: zmin,
  34040. xmax: xmax,
  34041. zmax: zmax,
  34042. subdivisions: subdivisions,
  34043. precision: precision,
  34044. updatable: updatable
  34045. };
  34046. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34047. };
  34048. /**
  34049. * Creates a ground mesh from a height map.
  34050. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34051. * Please consider using the same method from the MeshBuilder class instead.
  34052. * The parameter `url` sets the URL of the height map image resource.
  34053. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34054. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34055. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34056. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34057. * 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).
  34058. * This function is passed the newly built mesh :
  34059. * ```javascript
  34060. * function(mesh) { // do things
  34061. * return; }
  34062. * ```
  34063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34064. */
  34065. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34066. var options = {
  34067. width: width,
  34068. height: height,
  34069. subdivisions: subdivisions,
  34070. minHeight: minHeight,
  34071. maxHeight: maxHeight,
  34072. updatable: updatable,
  34073. onReady: onReady
  34074. };
  34075. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34076. };
  34077. /**
  34078. * Creates a tube mesh.
  34079. * 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.
  34080. * Please consider using the same method from the MeshBuilder class instead.
  34081. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34082. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34083. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34084. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34085. * 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.
  34086. * It must return a radius value (positive float) :
  34087. * ```javascript
  34088. * var radiusFunction = function(i, distance) {
  34089. * // do things
  34090. * return radius; }
  34091. * ```
  34092. * 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
  34093. * 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
  34094. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34095. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34096. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34097. */
  34098. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34099. var options = {
  34100. path: path,
  34101. radius: radius,
  34102. tessellation: tessellation,
  34103. radiusFunction: radiusFunction,
  34104. arc: 1,
  34105. cap: cap,
  34106. updatable: updatable,
  34107. sideOrientation: sideOrientation,
  34108. instance: instance
  34109. };
  34110. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34111. };
  34112. /**
  34113. * Creates a polyhedron mesh.
  34114. * Please consider using the same method from the MeshBuilder class instead.
  34115. * 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
  34116. * to choose the wanted type.
  34117. * The parameter `size` (positive float, default 1) sets the polygon size.
  34118. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34119. * 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`.
  34120. * 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
  34121. * 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)`).
  34122. * 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
  34123. * 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.
  34124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34125. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34127. */
  34128. Mesh.CreatePolyhedron = function (name, options, scene) {
  34129. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34130. };
  34131. /**
  34132. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34133. * Please consider using the same method from the MeshBuilder class instead.
  34134. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34135. * 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`).
  34136. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34137. * 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.
  34138. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34139. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34141. */
  34142. Mesh.CreateIcoSphere = function (name, options, scene) {
  34143. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34144. };
  34145. /**
  34146. * Creates a decal mesh.
  34147. * Please consider using the same method from the MeshBuilder class instead.
  34148. * 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.
  34149. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34150. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34151. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34152. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34153. */
  34154. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34155. var options = {
  34156. position: position,
  34157. normal: normal,
  34158. size: size,
  34159. angle: angle
  34160. };
  34161. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34162. };
  34163. // Skeletons
  34164. /**
  34165. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34166. */
  34167. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34168. if (!this._sourcePositions) {
  34169. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34170. if (!source) {
  34171. return this._sourcePositions;
  34172. }
  34173. this._sourcePositions = new Float32Array(source);
  34174. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34175. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34176. }
  34177. }
  34178. return this._sourcePositions;
  34179. };
  34180. /**
  34181. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34182. */
  34183. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34184. if (!this._sourceNormals) {
  34185. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34186. if (!source) {
  34187. return this._sourceNormals;
  34188. }
  34189. this._sourceNormals = new Float32Array(source);
  34190. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34191. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34192. }
  34193. }
  34194. return this._sourceNormals;
  34195. };
  34196. /**
  34197. * Updates the vertex buffer by applying transformation from the bones.
  34198. * Returns the Mesh.
  34199. *
  34200. * @param {skeleton} skeleton to apply
  34201. */
  34202. Mesh.prototype.applySkeleton = function (skeleton) {
  34203. if (!this.geometry) {
  34204. return this;
  34205. }
  34206. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34207. return this;
  34208. }
  34209. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34210. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34211. return this;
  34212. }
  34213. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34214. return this;
  34215. }
  34216. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34217. return this;
  34218. }
  34219. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34220. return this;
  34221. }
  34222. if (!this._sourcePositions) {
  34223. var submeshes = this.subMeshes.slice();
  34224. this.setPositionsForCPUSkinning();
  34225. this.subMeshes = submeshes;
  34226. }
  34227. if (!this._sourceNormals) {
  34228. this.setNormalsForCPUSkinning();
  34229. }
  34230. // positionsData checks for not being Float32Array will only pass at most once
  34231. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34232. if (!positionsData) {
  34233. return this;
  34234. }
  34235. if (!(positionsData instanceof Float32Array)) {
  34236. positionsData = new Float32Array(positionsData);
  34237. }
  34238. // normalsData checks for not being Float32Array will only pass at most once
  34239. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34240. if (!normalsData) {
  34241. return this;
  34242. }
  34243. if (!(normalsData instanceof Float32Array)) {
  34244. normalsData = new Float32Array(normalsData);
  34245. }
  34246. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34247. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34248. if (!matricesWeightsData || !matricesIndicesData) {
  34249. return this;
  34250. }
  34251. var needExtras = this.numBoneInfluencers > 4;
  34252. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34253. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34254. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34255. var tempVector3 = BABYLON.Vector3.Zero();
  34256. var finalMatrix = new BABYLON.Matrix();
  34257. var tempMatrix = new BABYLON.Matrix();
  34258. var matWeightIdx = 0;
  34259. var inf;
  34260. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34261. var weight;
  34262. for (inf = 0; inf < 4; inf++) {
  34263. weight = matricesWeightsData[matWeightIdx + inf];
  34264. if (weight > 0) {
  34265. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34266. finalMatrix.addToSelf(tempMatrix);
  34267. }
  34268. }
  34269. if (needExtras) {
  34270. for (inf = 0; inf < 4; inf++) {
  34271. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34272. if (weight > 0) {
  34273. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34274. finalMatrix.addToSelf(tempMatrix);
  34275. }
  34276. }
  34277. }
  34278. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34279. tempVector3.toArray(positionsData, index);
  34280. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34281. tempVector3.toArray(normalsData, index);
  34282. finalMatrix.reset();
  34283. }
  34284. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34285. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34286. return this;
  34287. };
  34288. // Tools
  34289. /**
  34290. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34291. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34292. */
  34293. Mesh.MinMax = function (meshes) {
  34294. var minVector = null;
  34295. var maxVector = null;
  34296. meshes.forEach(function (mesh, index, array) {
  34297. var boundingInfo = mesh.getBoundingInfo();
  34298. var boundingBox = boundingInfo.boundingBox;
  34299. if (!minVector || !maxVector) {
  34300. minVector = boundingBox.minimumWorld;
  34301. maxVector = boundingBox.maximumWorld;
  34302. }
  34303. else {
  34304. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34305. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34306. }
  34307. });
  34308. if (!minVector || !maxVector) {
  34309. return {
  34310. min: BABYLON.Vector3.Zero(),
  34311. max: BABYLON.Vector3.Zero()
  34312. };
  34313. }
  34314. return {
  34315. min: minVector,
  34316. max: maxVector
  34317. };
  34318. };
  34319. /**
  34320. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34321. */
  34322. Mesh.Center = function (meshesOrMinMaxVector) {
  34323. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34324. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34325. };
  34326. /**
  34327. * Merge the array of meshes into a single mesh for performance reasons.
  34328. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34329. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34330. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34331. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34332. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34333. */
  34334. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34335. if (disposeSource === void 0) { disposeSource = true; }
  34336. var index;
  34337. if (!allow32BitsIndices) {
  34338. var totalVertices = 0;
  34339. // Counting vertices
  34340. for (index = 0; index < meshes.length; index++) {
  34341. if (meshes[index]) {
  34342. totalVertices += meshes[index].getTotalVertices();
  34343. if (totalVertices > 65536) {
  34344. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34345. return null;
  34346. }
  34347. }
  34348. }
  34349. }
  34350. // Merge
  34351. var vertexData = null;
  34352. var otherVertexData;
  34353. var indiceArray = new Array();
  34354. var source = null;
  34355. for (index = 0; index < meshes.length; index++) {
  34356. if (meshes[index]) {
  34357. meshes[index].computeWorldMatrix(true);
  34358. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34359. otherVertexData.transform(meshes[index].getWorldMatrix());
  34360. if (vertexData) {
  34361. vertexData.merge(otherVertexData);
  34362. }
  34363. else {
  34364. vertexData = otherVertexData;
  34365. source = meshes[index];
  34366. }
  34367. if (subdivideWithSubMeshes) {
  34368. indiceArray.push(meshes[index].getTotalIndices());
  34369. }
  34370. }
  34371. }
  34372. source = source;
  34373. if (!meshSubclass) {
  34374. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34375. }
  34376. vertexData.applyToMesh(meshSubclass);
  34377. // Setting properties
  34378. meshSubclass.material = source.material;
  34379. meshSubclass.checkCollisions = source.checkCollisions;
  34380. // Cleaning
  34381. if (disposeSource) {
  34382. for (index = 0; index < meshes.length; index++) {
  34383. if (meshes[index]) {
  34384. meshes[index].dispose();
  34385. }
  34386. }
  34387. }
  34388. // Subdivide
  34389. if (subdivideWithSubMeshes) {
  34390. //-- removal of global submesh
  34391. meshSubclass.releaseSubMeshes();
  34392. index = 0;
  34393. var offset = 0;
  34394. //-- apply subdivision according to index table
  34395. while (index < indiceArray.length) {
  34396. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34397. offset += indiceArray[index];
  34398. index++;
  34399. }
  34400. }
  34401. return meshSubclass;
  34402. };
  34403. // Consts
  34404. Mesh._FRONTSIDE = 0;
  34405. Mesh._BACKSIDE = 1;
  34406. Mesh._DOUBLESIDE = 2;
  34407. Mesh._DEFAULTSIDE = 0;
  34408. Mesh._NO_CAP = 0;
  34409. Mesh._CAP_START = 1;
  34410. Mesh._CAP_END = 2;
  34411. Mesh._CAP_ALL = 3;
  34412. return Mesh;
  34413. }(BABYLON.AbstractMesh));
  34414. BABYLON.Mesh = Mesh;
  34415. })(BABYLON || (BABYLON = {}));
  34416. //# sourceMappingURL=babylon.mesh.js.map
  34417. var BABYLON;
  34418. (function (BABYLON) {
  34419. var BaseSubMesh = /** @class */ (function () {
  34420. function BaseSubMesh() {
  34421. }
  34422. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34423. get: function () {
  34424. return this._materialEffect;
  34425. },
  34426. enumerable: true,
  34427. configurable: true
  34428. });
  34429. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34430. if (defines === void 0) { defines = null; }
  34431. if (this._materialEffect === effect) {
  34432. if (!effect) {
  34433. this._materialDefines = null;
  34434. }
  34435. return;
  34436. }
  34437. this._materialDefines = defines;
  34438. this._materialEffect = effect;
  34439. };
  34440. return BaseSubMesh;
  34441. }());
  34442. BABYLON.BaseSubMesh = BaseSubMesh;
  34443. var SubMesh = /** @class */ (function (_super) {
  34444. __extends(SubMesh, _super);
  34445. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34446. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34447. var _this = _super.call(this) || this;
  34448. _this.materialIndex = materialIndex;
  34449. _this.verticesStart = verticesStart;
  34450. _this.verticesCount = verticesCount;
  34451. _this.indexStart = indexStart;
  34452. _this.indexCount = indexCount;
  34453. _this._renderId = 0;
  34454. _this._mesh = mesh;
  34455. _this._renderingMesh = renderingMesh || mesh;
  34456. mesh.subMeshes.push(_this);
  34457. _this._trianglePlanes = [];
  34458. _this._id = mesh.subMeshes.length - 1;
  34459. if (createBoundingBox) {
  34460. _this.refreshBoundingInfo();
  34461. mesh.computeWorldMatrix(true);
  34462. }
  34463. return _this;
  34464. }
  34465. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34466. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34467. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34468. };
  34469. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34470. get: function () {
  34471. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34472. },
  34473. enumerable: true,
  34474. configurable: true
  34475. });
  34476. /**
  34477. * Returns the submesh BoudingInfo object.
  34478. */
  34479. SubMesh.prototype.getBoundingInfo = function () {
  34480. if (this.IsGlobal) {
  34481. return this._mesh.getBoundingInfo();
  34482. }
  34483. return this._boundingInfo;
  34484. };
  34485. /**
  34486. * Sets the submesh BoundingInfo.
  34487. * Return the SubMesh.
  34488. */
  34489. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34490. this._boundingInfo = boundingInfo;
  34491. return this;
  34492. };
  34493. /**
  34494. * Returns the mesh of the current submesh.
  34495. */
  34496. SubMesh.prototype.getMesh = function () {
  34497. return this._mesh;
  34498. };
  34499. /**
  34500. * Returns the rendering mesh of the submesh.
  34501. */
  34502. SubMesh.prototype.getRenderingMesh = function () {
  34503. return this._renderingMesh;
  34504. };
  34505. /**
  34506. * Returns the submesh material.
  34507. */
  34508. SubMesh.prototype.getMaterial = function () {
  34509. var rootMaterial = this._renderingMesh.material;
  34510. if (rootMaterial === null || rootMaterial === undefined) {
  34511. return this._mesh.getScene().defaultMaterial;
  34512. }
  34513. else if (rootMaterial.getSubMaterial) {
  34514. var multiMaterial = rootMaterial;
  34515. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34516. if (this._currentMaterial !== effectiveMaterial) {
  34517. this._currentMaterial = effectiveMaterial;
  34518. this._materialDefines = null;
  34519. }
  34520. return effectiveMaterial;
  34521. }
  34522. return rootMaterial;
  34523. };
  34524. // Methods
  34525. /**
  34526. * Sets a new updated BoundingInfo object to the submesh.
  34527. * Returns the SubMesh.
  34528. */
  34529. SubMesh.prototype.refreshBoundingInfo = function () {
  34530. this._lastColliderWorldVertices = null;
  34531. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34532. return this;
  34533. }
  34534. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34535. if (!data) {
  34536. this._boundingInfo = this._mesh.getBoundingInfo();
  34537. return this;
  34538. }
  34539. var indices = this._renderingMesh.getIndices();
  34540. var extend;
  34541. //is this the only submesh?
  34542. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34543. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34544. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34545. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34546. }
  34547. else {
  34548. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34549. }
  34550. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34551. return this;
  34552. };
  34553. SubMesh.prototype._checkCollision = function (collider) {
  34554. var boundingInfo = this.getBoundingInfo();
  34555. return boundingInfo._checkCollision(collider);
  34556. };
  34557. /**
  34558. * Updates the submesh BoundingInfo.
  34559. * Returns the Submesh.
  34560. */
  34561. SubMesh.prototype.updateBoundingInfo = function (world) {
  34562. var boundingInfo = this.getBoundingInfo();
  34563. if (!boundingInfo) {
  34564. this.refreshBoundingInfo();
  34565. boundingInfo = this.getBoundingInfo();
  34566. }
  34567. boundingInfo.update(world);
  34568. return this;
  34569. };
  34570. /**
  34571. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34572. * Boolean returned.
  34573. */
  34574. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34575. var boundingInfo = this.getBoundingInfo();
  34576. if (!boundingInfo) {
  34577. return false;
  34578. }
  34579. return boundingInfo.isInFrustum(frustumPlanes);
  34580. };
  34581. /**
  34582. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34583. * Boolean returned.
  34584. */
  34585. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34586. var boundingInfo = this.getBoundingInfo();
  34587. if (!boundingInfo) {
  34588. return false;
  34589. }
  34590. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34591. };
  34592. /**
  34593. * Renders the submesh.
  34594. * Returns it.
  34595. */
  34596. SubMesh.prototype.render = function (enableAlphaMode) {
  34597. this._renderingMesh.render(this, enableAlphaMode);
  34598. return this;
  34599. };
  34600. /**
  34601. * Returns a new Index Buffer.
  34602. * Type returned : WebGLBuffer.
  34603. */
  34604. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34605. if (!this._linesIndexBuffer) {
  34606. var linesIndices = [];
  34607. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34608. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34609. }
  34610. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34611. this.linesIndexCount = linesIndices.length;
  34612. }
  34613. return this._linesIndexBuffer;
  34614. };
  34615. /**
  34616. * True is the passed Ray intersects the submesh bounding box.
  34617. * Boolean returned.
  34618. */
  34619. SubMesh.prototype.canIntersects = function (ray) {
  34620. var boundingInfo = this.getBoundingInfo();
  34621. if (!boundingInfo) {
  34622. return false;
  34623. }
  34624. return ray.intersectsBox(boundingInfo.boundingBox);
  34625. };
  34626. /**
  34627. * Returns an object IntersectionInfo.
  34628. */
  34629. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34630. var intersectInfo = null;
  34631. var material = this.getMaterial();
  34632. if (!material) {
  34633. return null;
  34634. }
  34635. switch (material.fillMode) {
  34636. case BABYLON.Material.PointListDrawMode:
  34637. case BABYLON.Material.LineListDrawMode:
  34638. case BABYLON.Material.LineLoopDrawMode:
  34639. case BABYLON.Material.LineStripDrawMode:
  34640. case BABYLON.Material.TriangleFanDrawMode:
  34641. case BABYLON.Material.TriangleStripDrawMode:
  34642. return null;
  34643. }
  34644. // LineMesh first as it's also a Mesh...
  34645. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34646. var lineMesh = this._mesh;
  34647. // Line test
  34648. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34649. var p0 = positions[indices[index]];
  34650. var p1 = positions[indices[index + 1]];
  34651. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34652. if (length < 0) {
  34653. continue;
  34654. }
  34655. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34656. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34657. if (fastCheck) {
  34658. break;
  34659. }
  34660. }
  34661. }
  34662. }
  34663. else {
  34664. // Triangles test
  34665. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34666. var p0 = positions[indices[index]];
  34667. var p1 = positions[indices[index + 1]];
  34668. var p2 = positions[indices[index + 2]];
  34669. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34670. if (currentIntersectInfo) {
  34671. if (currentIntersectInfo.distance < 0) {
  34672. continue;
  34673. }
  34674. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34675. intersectInfo = currentIntersectInfo;
  34676. intersectInfo.faceId = index / 3;
  34677. if (fastCheck) {
  34678. break;
  34679. }
  34680. }
  34681. }
  34682. }
  34683. }
  34684. return intersectInfo;
  34685. };
  34686. SubMesh.prototype._rebuild = function () {
  34687. if (this._linesIndexBuffer) {
  34688. this._linesIndexBuffer = null;
  34689. }
  34690. };
  34691. // Clone
  34692. /**
  34693. * Creates a new Submesh from the passed Mesh.
  34694. */
  34695. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34696. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34697. if (!this.IsGlobal) {
  34698. var boundingInfo = this.getBoundingInfo();
  34699. if (!boundingInfo) {
  34700. return result;
  34701. }
  34702. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34703. }
  34704. return result;
  34705. };
  34706. // Dispose
  34707. /**
  34708. * Disposes the Submesh.
  34709. * Returns nothing.
  34710. */
  34711. SubMesh.prototype.dispose = function () {
  34712. if (this._linesIndexBuffer) {
  34713. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34714. this._linesIndexBuffer = null;
  34715. }
  34716. // Remove from mesh
  34717. var index = this._mesh.subMeshes.indexOf(this);
  34718. this._mesh.subMeshes.splice(index, 1);
  34719. };
  34720. // Statics
  34721. /**
  34722. * Creates a new Submesh from the passed parameters :
  34723. * - materialIndex (integer) : the index of the main mesh material.
  34724. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34725. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34726. * - mesh (Mesh) : the main mesh to create the submesh from.
  34727. * - renderingMesh (optional Mesh) : rendering mesh.
  34728. */
  34729. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34730. var minVertexIndex = Number.MAX_VALUE;
  34731. var maxVertexIndex = -Number.MAX_VALUE;
  34732. renderingMesh = (renderingMesh || mesh);
  34733. var indices = renderingMesh.getIndices();
  34734. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34735. var vertexIndex = indices[index];
  34736. if (vertexIndex < minVertexIndex)
  34737. minVertexIndex = vertexIndex;
  34738. if (vertexIndex > maxVertexIndex)
  34739. maxVertexIndex = vertexIndex;
  34740. }
  34741. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34742. };
  34743. return SubMesh;
  34744. }(BaseSubMesh));
  34745. BABYLON.SubMesh = SubMesh;
  34746. })(BABYLON || (BABYLON = {}));
  34747. //# sourceMappingURL=babylon.subMesh.js.map
  34748. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34749. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34750. s = arguments[i];
  34751. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34752. t[p] = s[p];
  34753. }
  34754. return t;
  34755. };
  34756. var BABYLON;
  34757. (function (BABYLON) {
  34758. /**
  34759. * Manages the defines for the Material
  34760. */
  34761. var MaterialDefines = /** @class */ (function () {
  34762. function MaterialDefines() {
  34763. this._isDirty = true;
  34764. /** @hidden */
  34765. this._areLightsDirty = true;
  34766. /** @hidden */
  34767. this._areAttributesDirty = true;
  34768. /** @hidden */
  34769. this._areTexturesDirty = true;
  34770. /** @hidden */
  34771. this._areFresnelDirty = true;
  34772. /** @hidden */
  34773. this._areMiscDirty = true;
  34774. /** @hidden */
  34775. this._areImageProcessingDirty = true;
  34776. /** @hidden */
  34777. this._normals = false;
  34778. /** @hidden */
  34779. this._uvs = false;
  34780. /** @hidden */
  34781. this._needNormals = false;
  34782. /** @hidden */
  34783. this._needUVs = false;
  34784. }
  34785. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34786. /**
  34787. * Specifies if the material needs to be re-calculated
  34788. */
  34789. get: function () {
  34790. return this._isDirty;
  34791. },
  34792. enumerable: true,
  34793. configurable: true
  34794. });
  34795. /**
  34796. * Marks the material to indicate that it has been re-calculated
  34797. */
  34798. MaterialDefines.prototype.markAsProcessed = function () {
  34799. this._isDirty = false;
  34800. this._areAttributesDirty = false;
  34801. this._areTexturesDirty = false;
  34802. this._areFresnelDirty = false;
  34803. this._areLightsDirty = false;
  34804. this._areMiscDirty = false;
  34805. this._areImageProcessingDirty = false;
  34806. };
  34807. /**
  34808. * Marks the material to indicate that it needs to be re-calculated
  34809. */
  34810. MaterialDefines.prototype.markAsUnprocessed = function () {
  34811. this._isDirty = true;
  34812. };
  34813. /**
  34814. * Marks the material to indicate all of its defines need to be re-calculated
  34815. */
  34816. MaterialDefines.prototype.markAllAsDirty = function () {
  34817. this._areTexturesDirty = true;
  34818. this._areAttributesDirty = true;
  34819. this._areLightsDirty = true;
  34820. this._areFresnelDirty = true;
  34821. this._areMiscDirty = true;
  34822. this._areImageProcessingDirty = true;
  34823. this._isDirty = true;
  34824. };
  34825. /**
  34826. * Marks the material to indicate that image processing needs to be re-calculated
  34827. */
  34828. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34829. this._areImageProcessingDirty = true;
  34830. this._isDirty = true;
  34831. };
  34832. /**
  34833. * Marks the material to indicate the lights need to be re-calculated
  34834. */
  34835. MaterialDefines.prototype.markAsLightDirty = function () {
  34836. this._areLightsDirty = true;
  34837. this._isDirty = true;
  34838. };
  34839. /**
  34840. * Marks the attribute state as changed
  34841. */
  34842. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34843. this._areAttributesDirty = true;
  34844. this._isDirty = true;
  34845. };
  34846. /**
  34847. * Marks the texture state as changed
  34848. */
  34849. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34850. this._areTexturesDirty = true;
  34851. this._isDirty = true;
  34852. };
  34853. /**
  34854. * Marks the fresnel state as changed
  34855. */
  34856. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34857. this._areFresnelDirty = true;
  34858. this._isDirty = true;
  34859. };
  34860. /**
  34861. * Marks the misc state as changed
  34862. */
  34863. MaterialDefines.prototype.markAsMiscDirty = function () {
  34864. this._areMiscDirty = true;
  34865. this._isDirty = true;
  34866. };
  34867. /**
  34868. * Rebuilds the material defines
  34869. */
  34870. MaterialDefines.prototype.rebuild = function () {
  34871. if (this._keys) {
  34872. delete this._keys;
  34873. }
  34874. this._keys = [];
  34875. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34876. var key = _a[_i];
  34877. if (key[0] === "_") {
  34878. continue;
  34879. }
  34880. this._keys.push(key);
  34881. }
  34882. };
  34883. /**
  34884. * Specifies if two material defines are equal
  34885. * @param other - A material define instance to compare to
  34886. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34887. */
  34888. MaterialDefines.prototype.isEqual = function (other) {
  34889. if (this._keys.length !== other._keys.length) {
  34890. return false;
  34891. }
  34892. for (var index = 0; index < this._keys.length; index++) {
  34893. var prop = this._keys[index];
  34894. if (this[prop] !== other[prop]) {
  34895. return false;
  34896. }
  34897. }
  34898. return true;
  34899. };
  34900. /**
  34901. * Clones this instance's defines to another instance
  34902. * @param other - material defines to clone values to
  34903. */
  34904. MaterialDefines.prototype.cloneTo = function (other) {
  34905. if (this._keys.length !== other._keys.length) {
  34906. other._keys = this._keys.slice(0);
  34907. }
  34908. for (var index = 0; index < this._keys.length; index++) {
  34909. var prop = this._keys[index];
  34910. other[prop] = this[prop];
  34911. }
  34912. };
  34913. /**
  34914. * Resets the material define values
  34915. */
  34916. MaterialDefines.prototype.reset = function () {
  34917. for (var index = 0; index < this._keys.length; index++) {
  34918. var prop = this._keys[index];
  34919. var type = typeof this[prop];
  34920. switch (type) {
  34921. case "number":
  34922. this[prop] = 0;
  34923. break;
  34924. case "string":
  34925. this[prop] = "";
  34926. break;
  34927. default:
  34928. this[prop] = false;
  34929. break;
  34930. }
  34931. }
  34932. };
  34933. /**
  34934. * Converts the material define values to a string
  34935. * @returns - String of material define information
  34936. */
  34937. MaterialDefines.prototype.toString = function () {
  34938. var result = "";
  34939. for (var index = 0; index < this._keys.length; index++) {
  34940. var prop = this._keys[index];
  34941. var value = this[prop];
  34942. var type = typeof value;
  34943. switch (type) {
  34944. case "number":
  34945. case "string":
  34946. result += "#define " + prop + " " + value + "\n";
  34947. break;
  34948. default:
  34949. if (value) {
  34950. result += "#define " + prop + "\n";
  34951. }
  34952. break;
  34953. }
  34954. }
  34955. return result;
  34956. };
  34957. return MaterialDefines;
  34958. }());
  34959. BABYLON.MaterialDefines = MaterialDefines;
  34960. /**
  34961. * Base class for the main features of a material in Babylon.js
  34962. */
  34963. var Material = /** @class */ (function () {
  34964. /**
  34965. * Creates a material instance
  34966. * @param name defines the name of the material
  34967. * @param scene defines the scene to reference
  34968. * @param doNotAdd specifies if the material should be added to the scene
  34969. */
  34970. function Material(name, scene, doNotAdd) {
  34971. /**
  34972. * Specifies if the ready state should be checked on each call
  34973. */
  34974. this.checkReadyOnEveryCall = false;
  34975. /**
  34976. * Specifies if the ready state should be checked once
  34977. */
  34978. this.checkReadyOnlyOnce = false;
  34979. /**
  34980. * The state of the material
  34981. */
  34982. this.state = "";
  34983. /**
  34984. * The alpha value of the material
  34985. */
  34986. this._alpha = 1.0;
  34987. /**
  34988. * Specifies if back face culling is enabled
  34989. */
  34990. this._backFaceCulling = true;
  34991. /**
  34992. * Specifies if the material should be serialized
  34993. */
  34994. this.doNotSerialize = false;
  34995. /**
  34996. * Specifies if the effect should be stored on sub meshes
  34997. */
  34998. this.storeEffectOnSubMeshes = false;
  34999. /**
  35000. * An event triggered when the material is disposed
  35001. */
  35002. this.onDisposeObservable = new BABYLON.Observable();
  35003. /**
  35004. * An event triggered when the material is bound
  35005. */
  35006. this.onBindObservable = new BABYLON.Observable();
  35007. /**
  35008. * An event triggered when the material is unbound
  35009. */
  35010. this.onUnBindObservable = new BABYLON.Observable();
  35011. /**
  35012. * Stores the value of the alpha mode
  35013. */
  35014. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35015. /**
  35016. * Stores the state of the need depth pre-pass value
  35017. */
  35018. this._needDepthPrePass = false;
  35019. /**
  35020. * Specifies if depth writing should be disabled
  35021. */
  35022. this.disableDepthWrite = false;
  35023. /**
  35024. * Specifies if depth writing should be forced
  35025. */
  35026. this.forceDepthWrite = false;
  35027. /**
  35028. * Specifies if there should be a separate pass for culling
  35029. */
  35030. this.separateCullingPass = false;
  35031. /**
  35032. * Stores the state specifing if fog should be enabled
  35033. */
  35034. this._fogEnabled = true;
  35035. /**
  35036. * Stores the size of points
  35037. */
  35038. this.pointSize = 1.0;
  35039. /**
  35040. * Stores the z offset value
  35041. */
  35042. this.zOffset = 0;
  35043. /**
  35044. * Specifies if the material was previously ready
  35045. */
  35046. this._wasPreviouslyReady = false;
  35047. /**
  35048. * Stores the fill mode state
  35049. */
  35050. this._fillMode = Material.TriangleFillMode;
  35051. this.name = name;
  35052. this.id = name || BABYLON.Tools.RandomId();
  35053. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35054. this.uniqueId = this._scene.getUniqueId();
  35055. if (this._scene.useRightHandedSystem) {
  35056. this.sideOrientation = Material.ClockWiseSideOrientation;
  35057. }
  35058. else {
  35059. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35060. }
  35061. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35062. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35063. if (!doNotAdd) {
  35064. this._scene.materials.push(this);
  35065. }
  35066. }
  35067. Object.defineProperty(Material, "TriangleFillMode", {
  35068. /**
  35069. * Returns the triangle fill mode
  35070. */
  35071. get: function () {
  35072. return Material._TriangleFillMode;
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(Material, "WireFrameFillMode", {
  35078. /**
  35079. * Returns the wireframe mode
  35080. */
  35081. get: function () {
  35082. return Material._WireFrameFillMode;
  35083. },
  35084. enumerable: true,
  35085. configurable: true
  35086. });
  35087. Object.defineProperty(Material, "PointFillMode", {
  35088. /**
  35089. * Returns the point fill mode
  35090. */
  35091. get: function () {
  35092. return Material._PointFillMode;
  35093. },
  35094. enumerable: true,
  35095. configurable: true
  35096. });
  35097. Object.defineProperty(Material, "PointListDrawMode", {
  35098. /**
  35099. * Returns the point list draw mode
  35100. */
  35101. get: function () {
  35102. return Material._PointListDrawMode;
  35103. },
  35104. enumerable: true,
  35105. configurable: true
  35106. });
  35107. Object.defineProperty(Material, "LineListDrawMode", {
  35108. /**
  35109. * Returns the line list draw mode
  35110. */
  35111. get: function () {
  35112. return Material._LineListDrawMode;
  35113. },
  35114. enumerable: true,
  35115. configurable: true
  35116. });
  35117. Object.defineProperty(Material, "LineLoopDrawMode", {
  35118. /**
  35119. * Returns the line loop draw mode
  35120. */
  35121. get: function () {
  35122. return Material._LineLoopDrawMode;
  35123. },
  35124. enumerable: true,
  35125. configurable: true
  35126. });
  35127. Object.defineProperty(Material, "LineStripDrawMode", {
  35128. /**
  35129. * Returns the line strip draw mode
  35130. */
  35131. get: function () {
  35132. return Material._LineStripDrawMode;
  35133. },
  35134. enumerable: true,
  35135. configurable: true
  35136. });
  35137. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35138. /**
  35139. * Returns the triangle strip draw mode
  35140. */
  35141. get: function () {
  35142. return Material._TriangleStripDrawMode;
  35143. },
  35144. enumerable: true,
  35145. configurable: true
  35146. });
  35147. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35148. /**
  35149. * Returns the triangle fan draw mode
  35150. */
  35151. get: function () {
  35152. return Material._TriangleFanDrawMode;
  35153. },
  35154. enumerable: true,
  35155. configurable: true
  35156. });
  35157. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35158. /**
  35159. * Returns the clock-wise side orientation
  35160. */
  35161. get: function () {
  35162. return Material._ClockWiseSideOrientation;
  35163. },
  35164. enumerable: true,
  35165. configurable: true
  35166. });
  35167. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35168. /**
  35169. * Returns the counter clock-wise side orientation
  35170. */
  35171. get: function () {
  35172. return Material._CounterClockWiseSideOrientation;
  35173. },
  35174. enumerable: true,
  35175. configurable: true
  35176. });
  35177. Object.defineProperty(Material, "TextureDirtyFlag", {
  35178. /**
  35179. * Returns the dirty texture flag value
  35180. */
  35181. get: function () {
  35182. return Material._TextureDirtyFlag;
  35183. },
  35184. enumerable: true,
  35185. configurable: true
  35186. });
  35187. Object.defineProperty(Material, "LightDirtyFlag", {
  35188. /**
  35189. * Returns the dirty light flag value
  35190. */
  35191. get: function () {
  35192. return Material._LightDirtyFlag;
  35193. },
  35194. enumerable: true,
  35195. configurable: true
  35196. });
  35197. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35198. /**
  35199. * Returns the dirty fresnel flag value
  35200. */
  35201. get: function () {
  35202. return Material._FresnelDirtyFlag;
  35203. },
  35204. enumerable: true,
  35205. configurable: true
  35206. });
  35207. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35208. /**
  35209. * Returns the dirty attributes flag value
  35210. */
  35211. get: function () {
  35212. return Material._AttributesDirtyFlag;
  35213. },
  35214. enumerable: true,
  35215. configurable: true
  35216. });
  35217. Object.defineProperty(Material, "MiscDirtyFlag", {
  35218. /**
  35219. * Returns the dirty misc flag value
  35220. */
  35221. get: function () {
  35222. return Material._MiscDirtyFlag;
  35223. },
  35224. enumerable: true,
  35225. configurable: true
  35226. });
  35227. Object.defineProperty(Material.prototype, "alpha", {
  35228. /**
  35229. * Gets the alpha value of the material
  35230. */
  35231. get: function () {
  35232. return this._alpha;
  35233. },
  35234. /**
  35235. * Sets the alpha value of the material
  35236. */
  35237. set: function (value) {
  35238. if (this._alpha === value) {
  35239. return;
  35240. }
  35241. this._alpha = value;
  35242. this.markAsDirty(Material.MiscDirtyFlag);
  35243. },
  35244. enumerable: true,
  35245. configurable: true
  35246. });
  35247. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35248. /**
  35249. * Gets the back-face culling state
  35250. */
  35251. get: function () {
  35252. return this._backFaceCulling;
  35253. },
  35254. /**
  35255. * Sets the back-face culling state
  35256. */
  35257. set: function (value) {
  35258. if (this._backFaceCulling === value) {
  35259. return;
  35260. }
  35261. this._backFaceCulling = value;
  35262. this.markAsDirty(Material.TextureDirtyFlag);
  35263. },
  35264. enumerable: true,
  35265. configurable: true
  35266. });
  35267. Object.defineProperty(Material.prototype, "onDispose", {
  35268. /**
  35269. * Called during a dispose event
  35270. */
  35271. set: function (callback) {
  35272. if (this._onDisposeObserver) {
  35273. this.onDisposeObservable.remove(this._onDisposeObserver);
  35274. }
  35275. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35276. },
  35277. enumerable: true,
  35278. configurable: true
  35279. });
  35280. Object.defineProperty(Material.prototype, "onBind", {
  35281. /**
  35282. * Called during a bind event
  35283. */
  35284. set: function (callback) {
  35285. if (this._onBindObserver) {
  35286. this.onBindObservable.remove(this._onBindObserver);
  35287. }
  35288. this._onBindObserver = this.onBindObservable.add(callback);
  35289. },
  35290. enumerable: true,
  35291. configurable: true
  35292. });
  35293. Object.defineProperty(Material.prototype, "alphaMode", {
  35294. /**
  35295. * Gets the value of the alpha mode
  35296. */
  35297. get: function () {
  35298. return this._alphaMode;
  35299. },
  35300. /**
  35301. * Sets the value of the alpha mode.
  35302. *
  35303. * | Value | Type | Description |
  35304. * | --- | --- | --- |
  35305. * | 0 | ALPHA_DISABLE | |
  35306. * | 1 | ALPHA_ADD | |
  35307. * | 2 | ALPHA_COMBINE | |
  35308. * | 3 | ALPHA_SUBTRACT | |
  35309. * | 4 | ALPHA_MULTIPLY | |
  35310. * | 5 | ALPHA_MAXIMIZED | |
  35311. * | 6 | ALPHA_ONEONE | |
  35312. * | 7 | ALPHA_PREMULTIPLIED | |
  35313. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35314. * | 9 | ALPHA_INTERPOLATE | |
  35315. * | 10 | ALPHA_SCREENMODE | |
  35316. *
  35317. */
  35318. set: function (value) {
  35319. if (this._alphaMode === value) {
  35320. return;
  35321. }
  35322. this._alphaMode = value;
  35323. this.markAsDirty(Material.TextureDirtyFlag);
  35324. },
  35325. enumerable: true,
  35326. configurable: true
  35327. });
  35328. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35329. /**
  35330. * Gets the depth pre-pass value
  35331. */
  35332. get: function () {
  35333. return this._needDepthPrePass;
  35334. },
  35335. /**
  35336. * Sets the need depth pre-pass value
  35337. */
  35338. set: function (value) {
  35339. if (this._needDepthPrePass === value) {
  35340. return;
  35341. }
  35342. this._needDepthPrePass = value;
  35343. if (this._needDepthPrePass) {
  35344. this.checkReadyOnEveryCall = true;
  35345. }
  35346. },
  35347. enumerable: true,
  35348. configurable: true
  35349. });
  35350. Object.defineProperty(Material.prototype, "fogEnabled", {
  35351. /**
  35352. * Gets the value of the fog enabled state
  35353. */
  35354. get: function () {
  35355. return this._fogEnabled;
  35356. },
  35357. /**
  35358. * Sets the state for enabling fog
  35359. */
  35360. set: function (value) {
  35361. if (this._fogEnabled === value) {
  35362. return;
  35363. }
  35364. this._fogEnabled = value;
  35365. this.markAsDirty(Material.MiscDirtyFlag);
  35366. },
  35367. enumerable: true,
  35368. configurable: true
  35369. });
  35370. Object.defineProperty(Material.prototype, "wireframe", {
  35371. /**
  35372. * Gets a value specifying if wireframe mode is enabled
  35373. */
  35374. get: function () {
  35375. switch (this._fillMode) {
  35376. case Material.WireFrameFillMode:
  35377. case Material.LineListDrawMode:
  35378. case Material.LineLoopDrawMode:
  35379. case Material.LineStripDrawMode:
  35380. return true;
  35381. }
  35382. return this._scene.forceWireframe;
  35383. },
  35384. /**
  35385. * Sets the state of wireframe mode
  35386. */
  35387. set: function (value) {
  35388. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35389. },
  35390. enumerable: true,
  35391. configurable: true
  35392. });
  35393. Object.defineProperty(Material.prototype, "pointsCloud", {
  35394. /**
  35395. * Gets the value specifying if point clouds are enabled
  35396. */
  35397. get: function () {
  35398. switch (this._fillMode) {
  35399. case Material.PointFillMode:
  35400. case Material.PointListDrawMode:
  35401. return true;
  35402. }
  35403. return this._scene.forcePointsCloud;
  35404. },
  35405. /**
  35406. * Sets the state of point cloud mode
  35407. */
  35408. set: function (value) {
  35409. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35410. },
  35411. enumerable: true,
  35412. configurable: true
  35413. });
  35414. Object.defineProperty(Material.prototype, "fillMode", {
  35415. /**
  35416. * Gets the material fill mode
  35417. */
  35418. get: function () {
  35419. return this._fillMode;
  35420. },
  35421. /**
  35422. * Sets the material fill mode
  35423. */
  35424. set: function (value) {
  35425. if (this._fillMode === value) {
  35426. return;
  35427. }
  35428. this._fillMode = value;
  35429. this.markAsDirty(Material.MiscDirtyFlag);
  35430. },
  35431. enumerable: true,
  35432. configurable: true
  35433. });
  35434. /**
  35435. * Returns a string representation of the current material
  35436. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35437. * @returns a string with material information
  35438. */
  35439. Material.prototype.toString = function (fullDetails) {
  35440. var ret = "Name: " + this.name;
  35441. if (fullDetails) {
  35442. }
  35443. return ret;
  35444. };
  35445. /**
  35446. * Gets the class name of the material
  35447. * @returns a string with the class name of the material
  35448. */
  35449. Material.prototype.getClassName = function () {
  35450. return "Material";
  35451. };
  35452. Object.defineProperty(Material.prototype, "isFrozen", {
  35453. /**
  35454. * Specifies if updates for the material been locked
  35455. */
  35456. get: function () {
  35457. return this.checkReadyOnlyOnce;
  35458. },
  35459. enumerable: true,
  35460. configurable: true
  35461. });
  35462. /**
  35463. * Locks updates for the material
  35464. */
  35465. Material.prototype.freeze = function () {
  35466. this.checkReadyOnlyOnce = true;
  35467. };
  35468. /**
  35469. * Unlocks updates for the material
  35470. */
  35471. Material.prototype.unfreeze = function () {
  35472. this.checkReadyOnlyOnce = false;
  35473. };
  35474. /**
  35475. * Specifies if the material is ready to be used
  35476. * @param mesh defines the mesh to check
  35477. * @param useInstances specifies if instances should be used
  35478. * @returns a boolean indicating if the material is ready to be used
  35479. */
  35480. Material.prototype.isReady = function (mesh, useInstances) {
  35481. return true;
  35482. };
  35483. /**
  35484. * Specifies that the submesh is ready to be used
  35485. * @param mesh defines the mesh to check
  35486. * @param subMesh defines which submesh to check
  35487. * @param useInstances specifies that instances should be used
  35488. * @returns a boolean indicating that the submesh is ready or not
  35489. */
  35490. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35491. return false;
  35492. };
  35493. /**
  35494. * Returns the material effect
  35495. * @returns the effect associated with the material
  35496. */
  35497. Material.prototype.getEffect = function () {
  35498. return this._effect;
  35499. };
  35500. /**
  35501. * Returns the current scene
  35502. * @returns a Scene
  35503. */
  35504. Material.prototype.getScene = function () {
  35505. return this._scene;
  35506. };
  35507. /**
  35508. * Specifies if the material will require alpha blending
  35509. * @returns a boolean specifying if alpha blending is needed
  35510. */
  35511. Material.prototype.needAlphaBlending = function () {
  35512. return (this.alpha < 1.0);
  35513. };
  35514. /**
  35515. * Specifies if the mesh will require alpha blending
  35516. * @param mesh defines the mesh to check
  35517. * @returns a boolean specifying if alpha blending is needed for the mesh
  35518. */
  35519. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35520. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35521. };
  35522. /**
  35523. * Specifies if this material should be rendered in alpha test mode
  35524. * @returns a boolean specifying if an alpha test is needed.
  35525. */
  35526. Material.prototype.needAlphaTesting = function () {
  35527. return false;
  35528. };
  35529. /**
  35530. * Gets the texture used for the alpha test
  35531. * @returns the texture to use for alpha testing
  35532. */
  35533. Material.prototype.getAlphaTestTexture = function () {
  35534. return null;
  35535. };
  35536. /**
  35537. * Marks the material to indicate that it needs to be re-calculated
  35538. */
  35539. Material.prototype.markDirty = function () {
  35540. this._wasPreviouslyReady = false;
  35541. };
  35542. /** @hidden */
  35543. Material.prototype._preBind = function (effect, overrideOrientation) {
  35544. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35545. var engine = this._scene.getEngine();
  35546. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35547. var reverse = orientation === Material.ClockWiseSideOrientation;
  35548. engine.enableEffect(effect ? effect : this._effect);
  35549. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35550. return reverse;
  35551. };
  35552. /**
  35553. * Binds the material to the mesh
  35554. * @param world defines the world transformation matrix
  35555. * @param mesh defines the mesh to bind the material to
  35556. */
  35557. Material.prototype.bind = function (world, mesh) {
  35558. };
  35559. /**
  35560. * Binds the submesh to the material
  35561. * @param world defines the world transformation matrix
  35562. * @param mesh defines the mesh containing the submesh
  35563. * @param subMesh defines the submesh to bind the material to
  35564. */
  35565. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35566. };
  35567. /**
  35568. * Binds the world matrix to the material
  35569. * @param world defines the world transformation matrix
  35570. */
  35571. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35572. };
  35573. /**
  35574. * Binds the scene's uniform buffer to the effect.
  35575. * @param effect defines the effect to bind to the scene uniform buffer
  35576. * @param sceneUbo defines the uniform buffer storing scene data
  35577. */
  35578. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35579. sceneUbo.bindToEffect(effect, "Scene");
  35580. };
  35581. /**
  35582. * Binds the view matrix to the effect
  35583. * @param effect defines the effect to bind the view matrix to
  35584. */
  35585. Material.prototype.bindView = function (effect) {
  35586. if (!this._useUBO) {
  35587. effect.setMatrix("view", this.getScene().getViewMatrix());
  35588. }
  35589. else {
  35590. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35591. }
  35592. };
  35593. /**
  35594. * Binds the view projection matrix to the effect
  35595. * @param effect defines the effect to bind the view projection matrix to
  35596. */
  35597. Material.prototype.bindViewProjection = function (effect) {
  35598. if (!this._useUBO) {
  35599. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35600. }
  35601. else {
  35602. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35603. }
  35604. };
  35605. /**
  35606. * Specifies if material alpha testing should be turned on for the mesh
  35607. * @param mesh defines the mesh to check
  35608. */
  35609. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35610. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35611. };
  35612. /**
  35613. * Processes to execute after binding the material to a mesh
  35614. * @param mesh defines the rendered mesh
  35615. */
  35616. Material.prototype._afterBind = function (mesh) {
  35617. this._scene._cachedMaterial = this;
  35618. if (mesh) {
  35619. this._scene._cachedVisibility = mesh.visibility;
  35620. }
  35621. else {
  35622. this._scene._cachedVisibility = 1;
  35623. }
  35624. if (mesh) {
  35625. this.onBindObservable.notifyObservers(mesh);
  35626. }
  35627. if (this.disableDepthWrite) {
  35628. var engine = this._scene.getEngine();
  35629. this._cachedDepthWriteState = engine.getDepthWrite();
  35630. engine.setDepthWrite(false);
  35631. }
  35632. };
  35633. /**
  35634. * Unbinds the material from the mesh
  35635. */
  35636. Material.prototype.unbind = function () {
  35637. this.onUnBindObservable.notifyObservers(this);
  35638. if (this.disableDepthWrite) {
  35639. var engine = this._scene.getEngine();
  35640. engine.setDepthWrite(this._cachedDepthWriteState);
  35641. }
  35642. };
  35643. /**
  35644. * Gets the active textures from the material
  35645. * @returns an array of textures
  35646. */
  35647. Material.prototype.getActiveTextures = function () {
  35648. return [];
  35649. };
  35650. /**
  35651. * Specifies if the material uses a texture
  35652. * @param texture defines the texture to check against the material
  35653. * @returns a boolean specifying if the material uses the texture
  35654. */
  35655. Material.prototype.hasTexture = function (texture) {
  35656. return false;
  35657. };
  35658. /**
  35659. * Makes a duplicate of the material, and gives it a new name
  35660. * @param name defines the new name for the duplicated material
  35661. * @returns the cloned material
  35662. */
  35663. Material.prototype.clone = function (name) {
  35664. return null;
  35665. };
  35666. /**
  35667. * Gets the meshes bound to the material
  35668. * @returns an array of meshes bound to the material
  35669. */
  35670. Material.prototype.getBindedMeshes = function () {
  35671. var result = new Array();
  35672. for (var index = 0; index < this._scene.meshes.length; index++) {
  35673. var mesh = this._scene.meshes[index];
  35674. if (mesh.material === this) {
  35675. result.push(mesh);
  35676. }
  35677. }
  35678. return result;
  35679. };
  35680. /**
  35681. * Force shader compilation
  35682. * @param mesh defines the mesh associated with this material
  35683. * @param onCompiled defines a function to execute once the material is compiled
  35684. * @param options defines the options to configure the compilation
  35685. */
  35686. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35687. var _this = this;
  35688. var localOptions = __assign({ clipPlane: false }, options);
  35689. var subMesh = new BABYLON.BaseSubMesh();
  35690. var scene = this.getScene();
  35691. var checkReady = function () {
  35692. if (!_this._scene || !_this._scene.getEngine()) {
  35693. return;
  35694. }
  35695. if (subMesh._materialDefines) {
  35696. subMesh._materialDefines._renderId = -1;
  35697. }
  35698. var clipPlaneState = scene.clipPlane;
  35699. if (localOptions.clipPlane) {
  35700. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35701. }
  35702. if (_this.storeEffectOnSubMeshes) {
  35703. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35704. if (onCompiled) {
  35705. onCompiled(_this);
  35706. }
  35707. }
  35708. else {
  35709. setTimeout(checkReady, 16);
  35710. }
  35711. }
  35712. else {
  35713. if (_this.isReady(mesh)) {
  35714. if (onCompiled) {
  35715. onCompiled(_this);
  35716. }
  35717. }
  35718. else {
  35719. setTimeout(checkReady, 16);
  35720. }
  35721. }
  35722. if (localOptions.clipPlane) {
  35723. scene.clipPlane = clipPlaneState;
  35724. }
  35725. };
  35726. checkReady();
  35727. };
  35728. /**
  35729. * Force shader compilation
  35730. * @param mesh defines the mesh that will use this material
  35731. * @param options defines additional options for compiling the shaders
  35732. * @returns a promise that resolves when the compilation completes
  35733. */
  35734. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35735. var _this = this;
  35736. return new Promise(function (resolve) {
  35737. _this.forceCompilation(mesh, function () {
  35738. resolve();
  35739. }, options);
  35740. });
  35741. };
  35742. /**
  35743. * Marks a define in the material to indicate that it needs to be re-computed
  35744. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35745. */
  35746. Material.prototype.markAsDirty = function (flag) {
  35747. if (flag & Material.TextureDirtyFlag) {
  35748. this._markAllSubMeshesAsTexturesDirty();
  35749. }
  35750. if (flag & Material.LightDirtyFlag) {
  35751. this._markAllSubMeshesAsLightsDirty();
  35752. }
  35753. if (flag & Material.FresnelDirtyFlag) {
  35754. this._markAllSubMeshesAsFresnelDirty();
  35755. }
  35756. if (flag & Material.AttributesDirtyFlag) {
  35757. this._markAllSubMeshesAsAttributesDirty();
  35758. }
  35759. if (flag & Material.MiscDirtyFlag) {
  35760. this._markAllSubMeshesAsMiscDirty();
  35761. }
  35762. this.getScene().resetCachedMaterial();
  35763. };
  35764. /**
  35765. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35766. * @param func defines a function which checks material defines against the submeshes
  35767. */
  35768. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35769. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35770. var mesh = _a[_i];
  35771. if (!mesh.subMeshes) {
  35772. continue;
  35773. }
  35774. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35775. var subMesh = _c[_b];
  35776. if (subMesh.getMaterial() !== this) {
  35777. continue;
  35778. }
  35779. if (!subMesh._materialDefines) {
  35780. continue;
  35781. }
  35782. func(subMesh._materialDefines);
  35783. }
  35784. }
  35785. };
  35786. /**
  35787. * Indicates that image processing needs to be re-calculated for all submeshes
  35788. */
  35789. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35790. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35791. };
  35792. /**
  35793. * Indicates that textures need to be re-calculated for all submeshes
  35794. */
  35795. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35796. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35797. };
  35798. /**
  35799. * Indicates that fresnel needs to be re-calculated for all submeshes
  35800. */
  35801. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35802. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35803. };
  35804. /**
  35805. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35806. */
  35807. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35808. this._markAllSubMeshesAsDirty(function (defines) {
  35809. defines.markAsFresnelDirty();
  35810. defines.markAsMiscDirty();
  35811. });
  35812. };
  35813. /**
  35814. * Indicates that lights need to be re-calculated for all submeshes
  35815. */
  35816. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35817. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35818. };
  35819. /**
  35820. * Indicates that attributes need to be re-calculated for all submeshes
  35821. */
  35822. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35823. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35824. };
  35825. /**
  35826. * Indicates that misc needs to be re-calculated for all submeshes
  35827. */
  35828. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35829. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35830. };
  35831. /**
  35832. * Indicates that textures and misc need to be re-calculated for all submeshes
  35833. */
  35834. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35835. this._markAllSubMeshesAsDirty(function (defines) {
  35836. defines.markAsTexturesDirty();
  35837. defines.markAsMiscDirty();
  35838. });
  35839. };
  35840. /**
  35841. * Disposes the material
  35842. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35843. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35844. */
  35845. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35846. // Animations
  35847. this.getScene().stopAnimation(this);
  35848. this.getScene().freeProcessedMaterials();
  35849. // Remove from scene
  35850. var index = this._scene.materials.indexOf(this);
  35851. if (index >= 0) {
  35852. this._scene.materials.splice(index, 1);
  35853. }
  35854. // Remove from meshes
  35855. for (index = 0; index < this._scene.meshes.length; index++) {
  35856. var mesh = this._scene.meshes[index];
  35857. if (mesh.material === this) {
  35858. mesh.material = null;
  35859. if (mesh.geometry) {
  35860. var geometry = (mesh.geometry);
  35861. if (this.storeEffectOnSubMeshes) {
  35862. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35863. var subMesh = _a[_i];
  35864. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35865. if (forceDisposeEffect && subMesh._materialEffect) {
  35866. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35867. }
  35868. }
  35869. }
  35870. else {
  35871. geometry._releaseVertexArrayObject(this._effect);
  35872. }
  35873. }
  35874. }
  35875. }
  35876. this._uniformBuffer.dispose();
  35877. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35878. if (forceDisposeEffect && this._effect) {
  35879. if (!this.storeEffectOnSubMeshes) {
  35880. this._scene.getEngine()._releaseEffect(this._effect);
  35881. }
  35882. this._effect = null;
  35883. }
  35884. // Callback
  35885. this.onDisposeObservable.notifyObservers(this);
  35886. this.onDisposeObservable.clear();
  35887. this.onBindObservable.clear();
  35888. this.onUnBindObservable.clear();
  35889. };
  35890. /**
  35891. * Serializes this material
  35892. * @returns the serialized material object
  35893. */
  35894. Material.prototype.serialize = function () {
  35895. return BABYLON.SerializationHelper.Serialize(this);
  35896. };
  35897. /**
  35898. * Creates a MultiMaterial from parsed MultiMaterial data.
  35899. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35900. * @param scene defines the hosting scene
  35901. * @returns a new MultiMaterial
  35902. */
  35903. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35904. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35905. multiMaterial.id = parsedMultiMaterial.id;
  35906. if (BABYLON.Tags) {
  35907. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35908. }
  35909. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35910. var subMatId = parsedMultiMaterial.materials[matIndex];
  35911. if (subMatId) {
  35912. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35913. }
  35914. else {
  35915. multiMaterial.subMaterials.push(null);
  35916. }
  35917. }
  35918. return multiMaterial;
  35919. };
  35920. /**
  35921. * Creates a material from parsed material data
  35922. * @param parsedMaterial defines parsed material data
  35923. * @param scene defines the hosting scene
  35924. * @param rootUrl defines the root URL to use to load textures
  35925. * @returns a new material
  35926. */
  35927. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35928. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35929. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35930. }
  35931. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35932. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35933. if (!BABYLON.LegacyPBRMaterial) {
  35934. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35935. return;
  35936. }
  35937. }
  35938. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35939. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35940. };
  35941. // Triangle views
  35942. Material._TriangleFillMode = 0;
  35943. Material._WireFrameFillMode = 1;
  35944. Material._PointFillMode = 2;
  35945. // Draw modes
  35946. Material._PointListDrawMode = 3;
  35947. Material._LineListDrawMode = 4;
  35948. Material._LineLoopDrawMode = 5;
  35949. Material._LineStripDrawMode = 6;
  35950. Material._TriangleStripDrawMode = 7;
  35951. Material._TriangleFanDrawMode = 8;
  35952. /**
  35953. * Stores the clock-wise side orientation
  35954. */
  35955. Material._ClockWiseSideOrientation = 0;
  35956. /**
  35957. * Stores the counter clock-wise side orientation
  35958. */
  35959. Material._CounterClockWiseSideOrientation = 1;
  35960. /**
  35961. * The dirty texture flag value
  35962. */
  35963. Material._TextureDirtyFlag = 1;
  35964. /**
  35965. * The dirty light flag value
  35966. */
  35967. Material._LightDirtyFlag = 2;
  35968. /**
  35969. * The dirty fresnel flag value
  35970. */
  35971. Material._FresnelDirtyFlag = 4;
  35972. /**
  35973. * The dirty attribute flag value
  35974. */
  35975. Material._AttributesDirtyFlag = 8;
  35976. /**
  35977. * The dirty misc flag value
  35978. */
  35979. Material._MiscDirtyFlag = 16;
  35980. __decorate([
  35981. BABYLON.serialize()
  35982. ], Material.prototype, "id", void 0);
  35983. __decorate([
  35984. BABYLON.serialize()
  35985. ], Material.prototype, "uniqueId", void 0);
  35986. __decorate([
  35987. BABYLON.serialize()
  35988. ], Material.prototype, "name", void 0);
  35989. __decorate([
  35990. BABYLON.serialize()
  35991. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35992. __decorate([
  35993. BABYLON.serialize()
  35994. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35995. __decorate([
  35996. BABYLON.serialize()
  35997. ], Material.prototype, "state", void 0);
  35998. __decorate([
  35999. BABYLON.serialize("alpha")
  36000. ], Material.prototype, "_alpha", void 0);
  36001. __decorate([
  36002. BABYLON.serialize("backFaceCulling")
  36003. ], Material.prototype, "_backFaceCulling", void 0);
  36004. __decorate([
  36005. BABYLON.serialize()
  36006. ], Material.prototype, "sideOrientation", void 0);
  36007. __decorate([
  36008. BABYLON.serialize("alphaMode")
  36009. ], Material.prototype, "_alphaMode", void 0);
  36010. __decorate([
  36011. BABYLON.serialize()
  36012. ], Material.prototype, "_needDepthPrePass", void 0);
  36013. __decorate([
  36014. BABYLON.serialize()
  36015. ], Material.prototype, "disableDepthWrite", void 0);
  36016. __decorate([
  36017. BABYLON.serialize()
  36018. ], Material.prototype, "forceDepthWrite", void 0);
  36019. __decorate([
  36020. BABYLON.serialize()
  36021. ], Material.prototype, "separateCullingPass", void 0);
  36022. __decorate([
  36023. BABYLON.serialize("fogEnabled")
  36024. ], Material.prototype, "_fogEnabled", void 0);
  36025. __decorate([
  36026. BABYLON.serialize()
  36027. ], Material.prototype, "pointSize", void 0);
  36028. __decorate([
  36029. BABYLON.serialize()
  36030. ], Material.prototype, "zOffset", void 0);
  36031. __decorate([
  36032. BABYLON.serialize()
  36033. ], Material.prototype, "wireframe", null);
  36034. __decorate([
  36035. BABYLON.serialize()
  36036. ], Material.prototype, "pointsCloud", null);
  36037. __decorate([
  36038. BABYLON.serialize()
  36039. ], Material.prototype, "fillMode", null);
  36040. return Material;
  36041. }());
  36042. BABYLON.Material = Material;
  36043. })(BABYLON || (BABYLON = {}));
  36044. //# sourceMappingURL=babylon.material.js.map
  36045. var BABYLON;
  36046. (function (BABYLON) {
  36047. var UniformBuffer = /** @class */ (function () {
  36048. /**
  36049. * Uniform buffer objects.
  36050. *
  36051. * Handles blocks of uniform on the GPU.
  36052. *
  36053. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36054. *
  36055. * For more information, please refer to :
  36056. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36057. */
  36058. function UniformBuffer(engine, data, dynamic) {
  36059. this._engine = engine;
  36060. this._noUBO = !engine.supportsUniformBuffers;
  36061. this._dynamic = dynamic;
  36062. this._data = data || [];
  36063. this._uniformLocations = {};
  36064. this._uniformSizes = {};
  36065. this._uniformLocationPointer = 0;
  36066. this._needSync = false;
  36067. if (this._noUBO) {
  36068. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36069. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36070. this.updateFloat = this._updateFloatForEffect;
  36071. this.updateFloat2 = this._updateFloat2ForEffect;
  36072. this.updateFloat3 = this._updateFloat3ForEffect;
  36073. this.updateFloat4 = this._updateFloat4ForEffect;
  36074. this.updateMatrix = this._updateMatrixForEffect;
  36075. this.updateVector3 = this._updateVector3ForEffect;
  36076. this.updateVector4 = this._updateVector4ForEffect;
  36077. this.updateColor3 = this._updateColor3ForEffect;
  36078. this.updateColor4 = this._updateColor4ForEffect;
  36079. }
  36080. else {
  36081. this._engine._uniformBuffers.push(this);
  36082. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36083. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36084. this.updateFloat = this._updateFloatForUniform;
  36085. this.updateFloat2 = this._updateFloat2ForUniform;
  36086. this.updateFloat3 = this._updateFloat3ForUniform;
  36087. this.updateFloat4 = this._updateFloat4ForUniform;
  36088. this.updateMatrix = this._updateMatrixForUniform;
  36089. this.updateVector3 = this._updateVector3ForUniform;
  36090. this.updateVector4 = this._updateVector4ForUniform;
  36091. this.updateColor3 = this._updateColor3ForUniform;
  36092. this.updateColor4 = this._updateColor4ForUniform;
  36093. }
  36094. }
  36095. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36096. // Properties
  36097. /**
  36098. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36099. * or just falling back on setUniformXXX calls.
  36100. */
  36101. get: function () {
  36102. return !this._noUBO;
  36103. },
  36104. enumerable: true,
  36105. configurable: true
  36106. });
  36107. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36108. /**
  36109. * Indicates if the WebGL underlying uniform buffer is in sync
  36110. * with the javascript cache data.
  36111. */
  36112. get: function () {
  36113. return !this._needSync;
  36114. },
  36115. enumerable: true,
  36116. configurable: true
  36117. });
  36118. /**
  36119. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36120. * Also, a dynamic UniformBuffer will disable cache verification and always
  36121. * update the underlying WebGL uniform buffer to the GPU.
  36122. */
  36123. UniformBuffer.prototype.isDynamic = function () {
  36124. return this._dynamic !== undefined;
  36125. };
  36126. /**
  36127. * The data cache on JS side.
  36128. */
  36129. UniformBuffer.prototype.getData = function () {
  36130. return this._bufferData;
  36131. };
  36132. /**
  36133. * The underlying WebGL Uniform buffer.
  36134. */
  36135. UniformBuffer.prototype.getBuffer = function () {
  36136. return this._buffer;
  36137. };
  36138. /**
  36139. * std140 layout specifies how to align data within an UBO structure.
  36140. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36141. * for specs.
  36142. */
  36143. UniformBuffer.prototype._fillAlignment = function (size) {
  36144. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36145. // and 4x4 matrices
  36146. // TODO : change if other types are used
  36147. var alignment;
  36148. if (size <= 2) {
  36149. alignment = size;
  36150. }
  36151. else {
  36152. alignment = 4;
  36153. }
  36154. if ((this._uniformLocationPointer % alignment) !== 0) {
  36155. var oldPointer = this._uniformLocationPointer;
  36156. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36157. var diff = this._uniformLocationPointer - oldPointer;
  36158. for (var i = 0; i < diff; i++) {
  36159. this._data.push(0);
  36160. }
  36161. }
  36162. };
  36163. /**
  36164. * Adds an uniform in the buffer.
  36165. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36166. * for the layout to be correct !
  36167. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36168. * @param {number|number[]} size Data size, or data directly.
  36169. */
  36170. UniformBuffer.prototype.addUniform = function (name, size) {
  36171. if (this._noUBO) {
  36172. return;
  36173. }
  36174. if (this._uniformLocations[name] !== undefined) {
  36175. // Already existing uniform
  36176. return;
  36177. }
  36178. // This function must be called in the order of the shader layout !
  36179. // size can be the size of the uniform, or data directly
  36180. var data;
  36181. if (size instanceof Array) {
  36182. data = size;
  36183. size = data.length;
  36184. }
  36185. else {
  36186. size = size;
  36187. data = [];
  36188. // Fill with zeros
  36189. for (var i = 0; i < size; i++) {
  36190. data.push(0);
  36191. }
  36192. }
  36193. this._fillAlignment(size);
  36194. this._uniformSizes[name] = size;
  36195. this._uniformLocations[name] = this._uniformLocationPointer;
  36196. this._uniformLocationPointer += size;
  36197. for (var i = 0; i < size; i++) {
  36198. this._data.push(data[i]);
  36199. }
  36200. this._needSync = true;
  36201. };
  36202. /**
  36203. * Wrapper for addUniform.
  36204. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36205. * @param {Matrix} mat A 4x4 matrix.
  36206. */
  36207. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36208. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36209. };
  36210. /**
  36211. * Wrapper for addUniform.
  36212. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36213. * @param {number} x
  36214. * @param {number} y
  36215. */
  36216. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36217. var temp = [x, y];
  36218. this.addUniform(name, temp);
  36219. };
  36220. /**
  36221. * Wrapper for addUniform.
  36222. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36223. * @param {number} x
  36224. * @param {number} y
  36225. * @param {number} z
  36226. */
  36227. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36228. var temp = [x, y, z];
  36229. this.addUniform(name, temp);
  36230. };
  36231. /**
  36232. * Wrapper for addUniform.
  36233. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36234. * @param {Color3} color
  36235. */
  36236. UniformBuffer.prototype.addColor3 = function (name, color) {
  36237. var temp = new Array();
  36238. color.toArray(temp);
  36239. this.addUniform(name, temp);
  36240. };
  36241. /**
  36242. * Wrapper for addUniform.
  36243. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36244. * @param {Color3} color
  36245. * @param {number} alpha
  36246. */
  36247. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36248. var temp = new Array();
  36249. color.toArray(temp);
  36250. temp.push(alpha);
  36251. this.addUniform(name, temp);
  36252. };
  36253. /**
  36254. * Wrapper for addUniform.
  36255. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36256. * @param {Vector3} vector
  36257. */
  36258. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36259. var temp = new Array();
  36260. vector.toArray(temp);
  36261. this.addUniform(name, temp);
  36262. };
  36263. /**
  36264. * Wrapper for addUniform.
  36265. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36266. */
  36267. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36268. this.addUniform(name, 12);
  36269. };
  36270. /**
  36271. * Wrapper for addUniform.
  36272. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36273. */
  36274. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36275. this.addUniform(name, 8);
  36276. };
  36277. /**
  36278. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36279. */
  36280. UniformBuffer.prototype.create = function () {
  36281. if (this._noUBO) {
  36282. return;
  36283. }
  36284. if (this._buffer) {
  36285. return; // nothing to do
  36286. }
  36287. // See spec, alignment must be filled as a vec4
  36288. this._fillAlignment(4);
  36289. this._bufferData = new Float32Array(this._data);
  36290. this._rebuild();
  36291. this._needSync = true;
  36292. };
  36293. UniformBuffer.prototype._rebuild = function () {
  36294. if (this._noUBO) {
  36295. return;
  36296. }
  36297. if (this._dynamic) {
  36298. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36299. }
  36300. else {
  36301. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36302. }
  36303. };
  36304. /**
  36305. * Updates the WebGL Uniform Buffer on the GPU.
  36306. * If the `dynamic` flag is set to true, no cache comparison is done.
  36307. * Otherwise, the buffer will be updated only if the cache differs.
  36308. */
  36309. UniformBuffer.prototype.update = function () {
  36310. if (!this._buffer) {
  36311. this.create();
  36312. return;
  36313. }
  36314. if (!this._dynamic && !this._needSync) {
  36315. return;
  36316. }
  36317. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36318. this._needSync = false;
  36319. };
  36320. /**
  36321. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36322. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36323. * @param {number[]|Float32Array} data Flattened data
  36324. * @param {number} size Size of the data.
  36325. */
  36326. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36327. var location = this._uniformLocations[uniformName];
  36328. if (location === undefined) {
  36329. if (this._buffer) {
  36330. // Cannot add an uniform if the buffer is already created
  36331. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36332. return;
  36333. }
  36334. this.addUniform(uniformName, size);
  36335. location = this._uniformLocations[uniformName];
  36336. }
  36337. if (!this._buffer) {
  36338. this.create();
  36339. }
  36340. if (!this._dynamic) {
  36341. // Cache for static uniform buffers
  36342. var changed = false;
  36343. for (var i = 0; i < size; i++) {
  36344. if (this._bufferData[location + i] !== data[i]) {
  36345. changed = true;
  36346. this._bufferData[location + i] = data[i];
  36347. }
  36348. }
  36349. this._needSync = this._needSync || changed;
  36350. }
  36351. else {
  36352. // No cache for dynamic
  36353. for (var i = 0; i < size; i++) {
  36354. this._bufferData[location + i] = data[i];
  36355. }
  36356. }
  36357. };
  36358. // Update methods
  36359. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36360. // To match std140, matrix must be realigned
  36361. for (var i = 0; i < 3; i++) {
  36362. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36363. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36364. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36365. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36366. }
  36367. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36368. };
  36369. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36370. this._currentEffect.setMatrix3x3(name, matrix);
  36371. };
  36372. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36373. this._currentEffect.setMatrix2x2(name, matrix);
  36374. };
  36375. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36376. // To match std140, matrix must be realigned
  36377. for (var i = 0; i < 2; i++) {
  36378. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36379. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36380. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36381. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36382. }
  36383. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36384. };
  36385. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36386. this._currentEffect.setFloat(name, x);
  36387. };
  36388. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36389. UniformBuffer._tempBuffer[0] = x;
  36390. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36391. };
  36392. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36393. if (suffix === void 0) { suffix = ""; }
  36394. this._currentEffect.setFloat2(name + suffix, x, y);
  36395. };
  36396. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36397. if (suffix === void 0) { suffix = ""; }
  36398. UniformBuffer._tempBuffer[0] = x;
  36399. UniformBuffer._tempBuffer[1] = y;
  36400. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36401. };
  36402. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36403. if (suffix === void 0) { suffix = ""; }
  36404. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36405. };
  36406. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36407. if (suffix === void 0) { suffix = ""; }
  36408. UniformBuffer._tempBuffer[0] = x;
  36409. UniformBuffer._tempBuffer[1] = y;
  36410. UniformBuffer._tempBuffer[2] = z;
  36411. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36412. };
  36413. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36414. if (suffix === void 0) { suffix = ""; }
  36415. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36416. };
  36417. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36418. if (suffix === void 0) { suffix = ""; }
  36419. UniformBuffer._tempBuffer[0] = x;
  36420. UniformBuffer._tempBuffer[1] = y;
  36421. UniformBuffer._tempBuffer[2] = z;
  36422. UniformBuffer._tempBuffer[3] = w;
  36423. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36424. };
  36425. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36426. this._currentEffect.setMatrix(name, mat);
  36427. };
  36428. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36429. this.updateUniform(name, mat.toArray(), 16);
  36430. };
  36431. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36432. this._currentEffect.setVector3(name, vector);
  36433. };
  36434. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36435. vector.toArray(UniformBuffer._tempBuffer);
  36436. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36437. };
  36438. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36439. this._currentEffect.setVector4(name, vector);
  36440. };
  36441. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36442. vector.toArray(UniformBuffer._tempBuffer);
  36443. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36444. };
  36445. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36446. if (suffix === void 0) { suffix = ""; }
  36447. this._currentEffect.setColor3(name + suffix, color);
  36448. };
  36449. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36450. if (suffix === void 0) { suffix = ""; }
  36451. color.toArray(UniformBuffer._tempBuffer);
  36452. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36453. };
  36454. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36455. if (suffix === void 0) { suffix = ""; }
  36456. this._currentEffect.setColor4(name + suffix, color, alpha);
  36457. };
  36458. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36459. if (suffix === void 0) { suffix = ""; }
  36460. color.toArray(UniformBuffer._tempBuffer);
  36461. UniformBuffer._tempBuffer[3] = alpha;
  36462. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36463. };
  36464. /**
  36465. * Sets a sampler uniform on the effect.
  36466. * @param {string} name Name of the sampler.
  36467. * @param {Texture} texture
  36468. */
  36469. UniformBuffer.prototype.setTexture = function (name, texture) {
  36470. this._currentEffect.setTexture(name, texture);
  36471. };
  36472. /**
  36473. * Directly updates the value of the uniform in the cache AND on the GPU.
  36474. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36475. * @param {number[]|Float32Array} data Flattened data
  36476. */
  36477. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36478. this.updateUniform(uniformName, data, data.length);
  36479. this.update();
  36480. };
  36481. /**
  36482. * Binds this uniform buffer to an effect.
  36483. * @param {Effect} effect
  36484. * @param {string} name Name of the uniform block in the shader.
  36485. */
  36486. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36487. this._currentEffect = effect;
  36488. if (this._noUBO || !this._buffer) {
  36489. return;
  36490. }
  36491. effect.bindUniformBuffer(this._buffer, name);
  36492. };
  36493. /**
  36494. * Disposes the uniform buffer.
  36495. */
  36496. UniformBuffer.prototype.dispose = function () {
  36497. if (this._noUBO) {
  36498. return;
  36499. }
  36500. var index = this._engine._uniformBuffers.indexOf(this);
  36501. if (index !== -1) {
  36502. this._engine._uniformBuffers.splice(index, 1);
  36503. }
  36504. if (!this._buffer) {
  36505. return;
  36506. }
  36507. if (this._engine._releaseBuffer(this._buffer)) {
  36508. this._buffer = null;
  36509. }
  36510. };
  36511. // Pool for avoiding memory leaks
  36512. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36513. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36514. return UniformBuffer;
  36515. }());
  36516. BABYLON.UniformBuffer = UniformBuffer;
  36517. })(BABYLON || (BABYLON = {}));
  36518. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36519. var BABYLON;
  36520. (function (BABYLON) {
  36521. /**
  36522. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36523. */
  36524. var VertexData = /** @class */ (function () {
  36525. function VertexData() {
  36526. }
  36527. /**
  36528. * Uses the passed data array to set the set the values for the specified kind of data
  36529. * @param data a linear array of floating numbers
  36530. * @param kind the type of data that is being set, eg positions, colors etc
  36531. */
  36532. VertexData.prototype.set = function (data, kind) {
  36533. switch (kind) {
  36534. case BABYLON.VertexBuffer.PositionKind:
  36535. this.positions = data;
  36536. break;
  36537. case BABYLON.VertexBuffer.NormalKind:
  36538. this.normals = data;
  36539. break;
  36540. case BABYLON.VertexBuffer.TangentKind:
  36541. this.tangents = data;
  36542. break;
  36543. case BABYLON.VertexBuffer.UVKind:
  36544. this.uvs = data;
  36545. break;
  36546. case BABYLON.VertexBuffer.UV2Kind:
  36547. this.uvs2 = data;
  36548. break;
  36549. case BABYLON.VertexBuffer.UV3Kind:
  36550. this.uvs3 = data;
  36551. break;
  36552. case BABYLON.VertexBuffer.UV4Kind:
  36553. this.uvs4 = data;
  36554. break;
  36555. case BABYLON.VertexBuffer.UV5Kind:
  36556. this.uvs5 = data;
  36557. break;
  36558. case BABYLON.VertexBuffer.UV6Kind:
  36559. this.uvs6 = data;
  36560. break;
  36561. case BABYLON.VertexBuffer.ColorKind:
  36562. this.colors = data;
  36563. break;
  36564. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36565. this.matricesIndices = data;
  36566. break;
  36567. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36568. this.matricesWeights = data;
  36569. break;
  36570. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36571. this.matricesIndicesExtra = data;
  36572. break;
  36573. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36574. this.matricesWeightsExtra = data;
  36575. break;
  36576. }
  36577. };
  36578. /**
  36579. * Associates the vertexData to the passed Mesh.
  36580. * Sets it as updatable or not (default `false`)
  36581. * @param mesh the mesh the vertexData is applied to
  36582. * @param updatable when used and having the value true allows new data to update the vertexData
  36583. * @returns the VertexData
  36584. */
  36585. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36586. this._applyTo(mesh, updatable);
  36587. return this;
  36588. };
  36589. /**
  36590. * Associates the vertexData to the passed Geometry.
  36591. * Sets it as updatable or not (default `false`)
  36592. * @param geometry the geometry the vertexData is applied to
  36593. * @param updatable when used and having the value true allows new data to update the vertexData
  36594. * @returns VertexData
  36595. */
  36596. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36597. this._applyTo(geometry, updatable);
  36598. return this;
  36599. };
  36600. /**
  36601. * Updates the associated mesh
  36602. * @param mesh the mesh to be updated
  36603. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36604. * @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
  36605. * @returns VertexData
  36606. */
  36607. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36608. this._update(mesh);
  36609. return this;
  36610. };
  36611. /**
  36612. * Updates the associated geometry
  36613. * @param geometry the geometry to be updated
  36614. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36615. * @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
  36616. * @returns VertexData.
  36617. */
  36618. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36619. this._update(geometry);
  36620. return this;
  36621. };
  36622. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36623. if (updatable === void 0) { updatable = false; }
  36624. if (this.positions) {
  36625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36626. }
  36627. if (this.normals) {
  36628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36629. }
  36630. if (this.tangents) {
  36631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36632. }
  36633. if (this.uvs) {
  36634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36635. }
  36636. if (this.uvs2) {
  36637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36638. }
  36639. if (this.uvs3) {
  36640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36641. }
  36642. if (this.uvs4) {
  36643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36644. }
  36645. if (this.uvs5) {
  36646. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36647. }
  36648. if (this.uvs6) {
  36649. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36650. }
  36651. if (this.colors) {
  36652. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36653. }
  36654. if (this.matricesIndices) {
  36655. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36656. }
  36657. if (this.matricesWeights) {
  36658. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36659. }
  36660. if (this.matricesIndicesExtra) {
  36661. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36662. }
  36663. if (this.matricesWeightsExtra) {
  36664. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36665. }
  36666. if (this.indices) {
  36667. meshOrGeometry.setIndices(this.indices, null, updatable);
  36668. }
  36669. else {
  36670. meshOrGeometry.setIndices([], null);
  36671. }
  36672. return this;
  36673. };
  36674. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36675. if (this.positions) {
  36676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36677. }
  36678. if (this.normals) {
  36679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36680. }
  36681. if (this.tangents) {
  36682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36683. }
  36684. if (this.uvs) {
  36685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36686. }
  36687. if (this.uvs2) {
  36688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36689. }
  36690. if (this.uvs3) {
  36691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36692. }
  36693. if (this.uvs4) {
  36694. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36695. }
  36696. if (this.uvs5) {
  36697. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36698. }
  36699. if (this.uvs6) {
  36700. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36701. }
  36702. if (this.colors) {
  36703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36704. }
  36705. if (this.matricesIndices) {
  36706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36707. }
  36708. if (this.matricesWeights) {
  36709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36710. }
  36711. if (this.matricesIndicesExtra) {
  36712. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36713. }
  36714. if (this.matricesWeightsExtra) {
  36715. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36716. }
  36717. if (this.indices) {
  36718. meshOrGeometry.setIndices(this.indices, null);
  36719. }
  36720. return this;
  36721. };
  36722. /**
  36723. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36724. * @param matrix the transforming matrix
  36725. * @returns the VertexData
  36726. */
  36727. VertexData.prototype.transform = function (matrix) {
  36728. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36729. var transformed = BABYLON.Vector3.Zero();
  36730. var index;
  36731. if (this.positions) {
  36732. var position = BABYLON.Vector3.Zero();
  36733. for (index = 0; index < this.positions.length; index += 3) {
  36734. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36735. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36736. this.positions[index] = transformed.x;
  36737. this.positions[index + 1] = transformed.y;
  36738. this.positions[index + 2] = transformed.z;
  36739. }
  36740. }
  36741. if (this.normals) {
  36742. var normal = BABYLON.Vector3.Zero();
  36743. for (index = 0; index < this.normals.length; index += 3) {
  36744. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36745. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36746. this.normals[index] = transformed.x;
  36747. this.normals[index + 1] = transformed.y;
  36748. this.normals[index + 2] = transformed.z;
  36749. }
  36750. }
  36751. if (this.tangents) {
  36752. var tangent = BABYLON.Vector4.Zero();
  36753. var tangentTransformed = BABYLON.Vector4.Zero();
  36754. for (index = 0; index < this.tangents.length; index += 4) {
  36755. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36756. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36757. this.tangents[index] = tangentTransformed.x;
  36758. this.tangents[index + 1] = tangentTransformed.y;
  36759. this.tangents[index + 2] = tangentTransformed.z;
  36760. this.tangents[index + 3] = tangentTransformed.w;
  36761. }
  36762. }
  36763. if (flip && this.indices) {
  36764. for (index = 0; index < this.indices.length; index += 3) {
  36765. var tmp = this.indices[index + 1];
  36766. this.indices[index + 1] = this.indices[index + 2];
  36767. this.indices[index + 2] = tmp;
  36768. }
  36769. }
  36770. return this;
  36771. };
  36772. /**
  36773. * Merges the passed VertexData into the current one
  36774. * @param other the VertexData to be merged into the current one
  36775. * @returns the modified VertexData
  36776. */
  36777. VertexData.prototype.merge = function (other) {
  36778. this._validate();
  36779. other._validate();
  36780. if (!this.normals !== !other.normals ||
  36781. !this.tangents !== !other.tangents ||
  36782. !this.uvs !== !other.uvs ||
  36783. !this.uvs2 !== !other.uvs2 ||
  36784. !this.uvs3 !== !other.uvs3 ||
  36785. !this.uvs4 !== !other.uvs4 ||
  36786. !this.uvs5 !== !other.uvs5 ||
  36787. !this.uvs6 !== !other.uvs6 ||
  36788. !this.colors !== !other.colors ||
  36789. !this.matricesIndices !== !other.matricesIndices ||
  36790. !this.matricesWeights !== !other.matricesWeights ||
  36791. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36792. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36793. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36794. }
  36795. if (other.indices) {
  36796. if (!this.indices) {
  36797. this.indices = [];
  36798. }
  36799. var offset = this.positions ? this.positions.length / 3 : 0;
  36800. for (var index = 0; index < other.indices.length; index++) {
  36801. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36802. this.indices.push(other.indices[index] + offset);
  36803. }
  36804. }
  36805. this.positions = this._mergeElement(this.positions, other.positions);
  36806. this.normals = this._mergeElement(this.normals, other.normals);
  36807. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36808. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36809. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36810. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36811. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36812. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36813. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36814. this.colors = this._mergeElement(this.colors, other.colors);
  36815. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36816. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36817. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36818. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36819. return this;
  36820. };
  36821. VertexData.prototype._mergeElement = function (source, other) {
  36822. if (!source) {
  36823. return other;
  36824. }
  36825. if (!other) {
  36826. return source;
  36827. }
  36828. var len = other.length + source.length;
  36829. var isSrcTypedArray = source instanceof Float32Array;
  36830. var isOthTypedArray = other instanceof Float32Array;
  36831. // use non-loop method when the source is Float32Array
  36832. if (isSrcTypedArray) {
  36833. var ret32 = new Float32Array(len);
  36834. ret32.set(source);
  36835. ret32.set(other, source.length);
  36836. return ret32;
  36837. // source is number[], when other is also use concat
  36838. }
  36839. else if (!isOthTypedArray) {
  36840. return source.concat(other);
  36841. // source is a number[], but other is a Float32Array, loop required
  36842. }
  36843. else {
  36844. var ret = source.slice(0); // copy source to a separate array
  36845. for (var i = 0, len = other.length; i < len; i++) {
  36846. ret.push(other[i]);
  36847. }
  36848. return ret;
  36849. }
  36850. };
  36851. VertexData.prototype._validate = function () {
  36852. if (!this.positions) {
  36853. throw new Error("Positions are required");
  36854. }
  36855. var getElementCount = function (kind, values) {
  36856. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36857. if ((values.length % stride) !== 0) {
  36858. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36859. }
  36860. return values.length / stride;
  36861. };
  36862. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36863. var validateElementCount = function (kind, values) {
  36864. var elementCount = getElementCount(kind, values);
  36865. if (elementCount !== positionsElementCount) {
  36866. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36867. }
  36868. };
  36869. if (this.normals)
  36870. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36871. if (this.tangents)
  36872. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36873. if (this.uvs)
  36874. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36875. if (this.uvs2)
  36876. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36877. if (this.uvs3)
  36878. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36879. if (this.uvs4)
  36880. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36881. if (this.uvs5)
  36882. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36883. if (this.uvs6)
  36884. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36885. if (this.colors)
  36886. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36887. if (this.matricesIndices)
  36888. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36889. if (this.matricesWeights)
  36890. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36891. if (this.matricesIndicesExtra)
  36892. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36893. if (this.matricesWeightsExtra)
  36894. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36895. };
  36896. /**
  36897. * Serializes the VertexData
  36898. * @returns a serialized object
  36899. */
  36900. VertexData.prototype.serialize = function () {
  36901. var serializationObject = this.serialize();
  36902. if (this.positions) {
  36903. serializationObject.positions = this.positions;
  36904. }
  36905. if (this.normals) {
  36906. serializationObject.normals = this.normals;
  36907. }
  36908. if (this.tangents) {
  36909. serializationObject.tangents = this.tangents;
  36910. }
  36911. if (this.uvs) {
  36912. serializationObject.uvs = this.uvs;
  36913. }
  36914. if (this.uvs2) {
  36915. serializationObject.uvs2 = this.uvs2;
  36916. }
  36917. if (this.uvs3) {
  36918. serializationObject.uvs3 = this.uvs3;
  36919. }
  36920. if (this.uvs4) {
  36921. serializationObject.uvs4 = this.uvs4;
  36922. }
  36923. if (this.uvs5) {
  36924. serializationObject.uvs5 = this.uvs5;
  36925. }
  36926. if (this.uvs6) {
  36927. serializationObject.uvs6 = this.uvs6;
  36928. }
  36929. if (this.colors) {
  36930. serializationObject.colors = this.colors;
  36931. }
  36932. if (this.matricesIndices) {
  36933. serializationObject.matricesIndices = this.matricesIndices;
  36934. serializationObject.matricesIndices._isExpanded = true;
  36935. }
  36936. if (this.matricesWeights) {
  36937. serializationObject.matricesWeights = this.matricesWeights;
  36938. }
  36939. if (this.matricesIndicesExtra) {
  36940. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36941. serializationObject.matricesIndicesExtra._isExpanded = true;
  36942. }
  36943. if (this.matricesWeightsExtra) {
  36944. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36945. }
  36946. serializationObject.indices = this.indices;
  36947. return serializationObject;
  36948. };
  36949. // Statics
  36950. /**
  36951. * Extracts the vertexData from a mesh
  36952. * @param mesh the mesh from which to extract the VertexData
  36953. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36954. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36955. * @returns the object VertexData associated to the passed mesh
  36956. */
  36957. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36958. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36959. };
  36960. /**
  36961. * Extracts the vertexData from the geometry
  36962. * @param geometry the geometry from which to extract the VertexData
  36963. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36964. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36965. * @returns the object VertexData associated to the passed mesh
  36966. */
  36967. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36968. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36969. };
  36970. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36971. var result = new VertexData();
  36972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36973. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36974. }
  36975. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36976. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36977. }
  36978. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36979. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36980. }
  36981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36982. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36983. }
  36984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36985. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36986. }
  36987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36988. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36989. }
  36990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36991. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36992. }
  36993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36994. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36995. }
  36996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36997. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36998. }
  36999. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37000. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37001. }
  37002. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37003. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37004. }
  37005. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37006. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37007. }
  37008. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37009. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37010. }
  37011. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37012. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37013. }
  37014. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37015. return result;
  37016. };
  37017. /**
  37018. * Creates the VertexData for a Ribbon
  37019. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37020. * * pathArray array of paths, each of which an array of successive Vector3
  37021. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37022. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37023. * * 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
  37024. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37025. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37026. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37027. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37028. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37029. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37030. * @returns the VertexData of the ribbon
  37031. */
  37032. VertexData.CreateRibbon = function (options) {
  37033. var pathArray = options.pathArray;
  37034. var closeArray = options.closeArray || false;
  37035. var closePath = options.closePath || false;
  37036. var invertUV = options.invertUV || false;
  37037. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37038. var offset = options.offset || defaultOffset;
  37039. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37040. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37041. var customUV = options.uvs;
  37042. var customColors = options.colors;
  37043. var positions = [];
  37044. var indices = [];
  37045. var normals = [];
  37046. var uvs = [];
  37047. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37048. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37049. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37050. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37051. var minlg; // minimal length among all paths from pathArray
  37052. var lg = []; // array of path lengths : nb of vertex per path
  37053. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37054. var p; // path iterator
  37055. var i; // point iterator
  37056. var j; // point iterator
  37057. // if single path in pathArray
  37058. if (pathArray.length < 2) {
  37059. var ar1 = [];
  37060. var ar2 = [];
  37061. for (i = 0; i < pathArray[0].length - offset; i++) {
  37062. ar1.push(pathArray[0][i]);
  37063. ar2.push(pathArray[0][i + offset]);
  37064. }
  37065. pathArray = [ar1, ar2];
  37066. }
  37067. // positions and horizontal distances (u)
  37068. var idc = 0;
  37069. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37070. var path;
  37071. var l;
  37072. minlg = pathArray[0].length;
  37073. var vectlg;
  37074. var dist;
  37075. for (p = 0; p < pathArray.length; p++) {
  37076. uTotalDistance[p] = 0;
  37077. us[p] = [0];
  37078. path = pathArray[p];
  37079. l = path.length;
  37080. minlg = (minlg < l) ? minlg : l;
  37081. j = 0;
  37082. while (j < l) {
  37083. positions.push(path[j].x, path[j].y, path[j].z);
  37084. if (j > 0) {
  37085. vectlg = path[j].subtract(path[j - 1]).length();
  37086. dist = vectlg + uTotalDistance[p];
  37087. us[p].push(dist);
  37088. uTotalDistance[p] = dist;
  37089. }
  37090. j++;
  37091. }
  37092. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37093. j--;
  37094. positions.push(path[0].x, path[0].y, path[0].z);
  37095. vectlg = path[j].subtract(path[0]).length();
  37096. dist = vectlg + uTotalDistance[p];
  37097. us[p].push(dist);
  37098. uTotalDistance[p] = dist;
  37099. }
  37100. lg[p] = l + closePathCorr;
  37101. idx[p] = idc;
  37102. idc += (l + closePathCorr);
  37103. }
  37104. // vertical distances (v)
  37105. var path1;
  37106. var path2;
  37107. var vertex1 = null;
  37108. var vertex2 = null;
  37109. for (i = 0; i < minlg + closePathCorr; i++) {
  37110. vTotalDistance[i] = 0;
  37111. vs[i] = [0];
  37112. for (p = 0; p < pathArray.length - 1; p++) {
  37113. path1 = pathArray[p];
  37114. path2 = pathArray[p + 1];
  37115. if (i === minlg) { // closePath
  37116. vertex1 = path1[0];
  37117. vertex2 = path2[0];
  37118. }
  37119. else {
  37120. vertex1 = path1[i];
  37121. vertex2 = path2[i];
  37122. }
  37123. vectlg = vertex2.subtract(vertex1).length();
  37124. dist = vectlg + vTotalDistance[i];
  37125. vs[i].push(dist);
  37126. vTotalDistance[i] = dist;
  37127. }
  37128. if (closeArray && vertex2 && vertex1) {
  37129. path1 = pathArray[p];
  37130. path2 = pathArray[0];
  37131. if (i === minlg) { // closePath
  37132. vertex2 = path2[0];
  37133. }
  37134. vectlg = vertex2.subtract(vertex1).length();
  37135. dist = vectlg + vTotalDistance[i];
  37136. vTotalDistance[i] = dist;
  37137. }
  37138. }
  37139. // uvs
  37140. var u;
  37141. var v;
  37142. if (customUV) {
  37143. for (p = 0; p < customUV.length; p++) {
  37144. uvs.push(customUV[p].x, customUV[p].y);
  37145. }
  37146. }
  37147. else {
  37148. for (p = 0; p < pathArray.length; p++) {
  37149. for (i = 0; i < minlg + closePathCorr; i++) {
  37150. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37151. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37152. if (invertUV) {
  37153. uvs.push(v, u);
  37154. }
  37155. else {
  37156. uvs.push(u, v);
  37157. }
  37158. }
  37159. }
  37160. }
  37161. // indices
  37162. p = 0; // path index
  37163. var pi = 0; // positions array index
  37164. var l1 = lg[p] - 1; // path1 length
  37165. var l2 = lg[p + 1] - 1; // path2 length
  37166. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37167. var shft = idx[1] - idx[0]; // shift
  37168. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37169. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37170. // 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
  37171. indices.push(pi, pi + shft, pi + 1);
  37172. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37173. pi += 1;
  37174. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37175. p++;
  37176. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37177. shft = idx[0] - idx[p];
  37178. l1 = lg[p] - 1;
  37179. l2 = lg[0] - 1;
  37180. }
  37181. else {
  37182. shft = idx[p + 1] - idx[p];
  37183. l1 = lg[p] - 1;
  37184. l2 = lg[p + 1] - 1;
  37185. }
  37186. pi = idx[p];
  37187. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37188. }
  37189. }
  37190. // normals
  37191. VertexData.ComputeNormals(positions, indices, normals);
  37192. if (closePath) { // update both the first and last vertex normals to their average value
  37193. var indexFirst = 0;
  37194. var indexLast = 0;
  37195. for (p = 0; p < pathArray.length; p++) {
  37196. indexFirst = idx[p] * 3;
  37197. if (p + 1 < pathArray.length) {
  37198. indexLast = (idx[p + 1] - 1) * 3;
  37199. }
  37200. else {
  37201. indexLast = normals.length - 3;
  37202. }
  37203. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37204. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37205. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37206. normals[indexLast] = normals[indexFirst];
  37207. normals[indexLast + 1] = normals[indexFirst + 1];
  37208. normals[indexLast + 2] = normals[indexFirst + 2];
  37209. }
  37210. }
  37211. // sides
  37212. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37213. // Colors
  37214. var colors = null;
  37215. if (customColors) {
  37216. colors = new Float32Array(customColors.length * 4);
  37217. for (var c = 0; c < customColors.length; c++) {
  37218. colors[c * 4] = customColors[c].r;
  37219. colors[c * 4 + 1] = customColors[c].g;
  37220. colors[c * 4 + 2] = customColors[c].b;
  37221. colors[c * 4 + 3] = customColors[c].a;
  37222. }
  37223. }
  37224. // Result
  37225. var vertexData = new VertexData();
  37226. var positions32 = new Float32Array(positions);
  37227. var normals32 = new Float32Array(normals);
  37228. var uvs32 = new Float32Array(uvs);
  37229. vertexData.indices = indices;
  37230. vertexData.positions = positions32;
  37231. vertexData.normals = normals32;
  37232. vertexData.uvs = uvs32;
  37233. if (colors) {
  37234. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37235. }
  37236. if (closePath) {
  37237. vertexData._idx = idx;
  37238. }
  37239. return vertexData;
  37240. };
  37241. /**
  37242. * Creates the VertexData for a box
  37243. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37244. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37245. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37246. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37247. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37248. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37249. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37250. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37251. * * 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)
  37252. * * 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)
  37253. * @returns the VertexData of the box
  37254. */
  37255. VertexData.CreateBox = function (options) {
  37256. var normalsSource = [
  37257. new BABYLON.Vector3(0, 0, 1),
  37258. new BABYLON.Vector3(0, 0, -1),
  37259. new BABYLON.Vector3(1, 0, 0),
  37260. new BABYLON.Vector3(-1, 0, 0),
  37261. new BABYLON.Vector3(0, 1, 0),
  37262. new BABYLON.Vector3(0, -1, 0)
  37263. ];
  37264. var indices = [];
  37265. var positions = [];
  37266. var normals = [];
  37267. var uvs = [];
  37268. var width = options.width || options.size || 1;
  37269. var height = options.height || options.size || 1;
  37270. var depth = options.depth || options.size || 1;
  37271. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37272. var faceUV = options.faceUV || new Array(6);
  37273. var faceColors = options.faceColors;
  37274. var colors = [];
  37275. // default face colors and UV if undefined
  37276. for (var f = 0; f < 6; f++) {
  37277. if (faceUV[f] === undefined) {
  37278. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37279. }
  37280. if (faceColors && faceColors[f] === undefined) {
  37281. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37282. }
  37283. }
  37284. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37285. // Create each face in turn.
  37286. for (var index = 0; index < normalsSource.length; index++) {
  37287. var normal = normalsSource[index];
  37288. // Get two vectors perpendicular to the face normal and to each other.
  37289. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37290. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37291. // Six indices (two triangles) per face.
  37292. var verticesLength = positions.length / 3;
  37293. indices.push(verticesLength);
  37294. indices.push(verticesLength + 1);
  37295. indices.push(verticesLength + 2);
  37296. indices.push(verticesLength);
  37297. indices.push(verticesLength + 2);
  37298. indices.push(verticesLength + 3);
  37299. // Four vertices per face.
  37300. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37301. positions.push(vertex.x, vertex.y, vertex.z);
  37302. normals.push(normal.x, normal.y, normal.z);
  37303. uvs.push(faceUV[index].z, faceUV[index].w);
  37304. if (faceColors) {
  37305. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37306. }
  37307. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37308. positions.push(vertex.x, vertex.y, vertex.z);
  37309. normals.push(normal.x, normal.y, normal.z);
  37310. uvs.push(faceUV[index].x, faceUV[index].w);
  37311. if (faceColors) {
  37312. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37313. }
  37314. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37315. positions.push(vertex.x, vertex.y, vertex.z);
  37316. normals.push(normal.x, normal.y, normal.z);
  37317. uvs.push(faceUV[index].x, faceUV[index].y);
  37318. if (faceColors) {
  37319. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37320. }
  37321. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37322. positions.push(vertex.x, vertex.y, vertex.z);
  37323. normals.push(normal.x, normal.y, normal.z);
  37324. uvs.push(faceUV[index].z, faceUV[index].y);
  37325. if (faceColors) {
  37326. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37327. }
  37328. }
  37329. // sides
  37330. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37331. // Result
  37332. var vertexData = new VertexData();
  37333. vertexData.indices = indices;
  37334. vertexData.positions = positions;
  37335. vertexData.normals = normals;
  37336. vertexData.uvs = uvs;
  37337. if (faceColors) {
  37338. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37339. vertexData.colors = totalColors;
  37340. }
  37341. return vertexData;
  37342. };
  37343. /**
  37344. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37345. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37346. * * segments sets the number of horizontal strips optional, default 32
  37347. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37348. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37349. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37350. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37351. * * 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
  37352. * * 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
  37353. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37354. * * 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)
  37355. * * 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)
  37356. * @returns the VertexData of the ellipsoid
  37357. */
  37358. VertexData.CreateSphere = function (options) {
  37359. var segments = options.segments || 32;
  37360. var diameterX = options.diameterX || options.diameter || 1;
  37361. var diameterY = options.diameterY || options.diameter || 1;
  37362. var diameterZ = options.diameterZ || options.diameter || 1;
  37363. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37364. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37366. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37367. var totalZRotationSteps = 2 + segments;
  37368. var totalYRotationSteps = 2 * totalZRotationSteps;
  37369. var indices = [];
  37370. var positions = [];
  37371. var normals = [];
  37372. var uvs = [];
  37373. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37374. var normalizedZ = zRotationStep / totalZRotationSteps;
  37375. var angleZ = normalizedZ * Math.PI * slice;
  37376. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37377. var normalizedY = yRotationStep / totalYRotationSteps;
  37378. var angleY = normalizedY * Math.PI * 2 * arc;
  37379. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37380. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37381. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37382. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37383. var vertex = complete.multiply(radius);
  37384. var normal = complete.divide(radius).normalize();
  37385. positions.push(vertex.x, vertex.y, vertex.z);
  37386. normals.push(normal.x, normal.y, normal.z);
  37387. uvs.push(normalizedY, normalizedZ);
  37388. }
  37389. if (zRotationStep > 0) {
  37390. var verticesCount = positions.length / 3;
  37391. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37392. indices.push((firstIndex));
  37393. indices.push((firstIndex + 1));
  37394. indices.push(firstIndex + totalYRotationSteps + 1);
  37395. indices.push((firstIndex + totalYRotationSteps + 1));
  37396. indices.push((firstIndex + 1));
  37397. indices.push((firstIndex + totalYRotationSteps + 2));
  37398. }
  37399. }
  37400. }
  37401. // Sides
  37402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37403. // Result
  37404. var vertexData = new VertexData();
  37405. vertexData.indices = indices;
  37406. vertexData.positions = positions;
  37407. vertexData.normals = normals;
  37408. vertexData.uvs = uvs;
  37409. return vertexData;
  37410. };
  37411. /**
  37412. * Creates the VertexData for a cylinder, cone or prism
  37413. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37414. * * height sets the height (y direction) of the cylinder, optional, default 2
  37415. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37416. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37417. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37418. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37419. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37420. * * 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
  37421. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37422. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37423. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37424. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37425. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37426. * * 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)
  37427. * * 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)
  37428. * @returns the VertexData of the cylinder, cone or prism
  37429. */
  37430. VertexData.CreateCylinder = function (options) {
  37431. var height = options.height || 2;
  37432. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37433. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37434. var tessellation = options.tessellation || 24;
  37435. var subdivisions = options.subdivisions || 1;
  37436. var hasRings = options.hasRings ? true : false;
  37437. var enclose = options.enclose ? true : false;
  37438. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37439. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37440. var faceUV = options.faceUV || new Array(3);
  37441. var faceColors = options.faceColors;
  37442. // default face colors and UV if undefined
  37443. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37444. var ringNb = (hasRings) ? subdivisions : 1;
  37445. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37446. var f;
  37447. for (f = 0; f < surfaceNb; f++) {
  37448. if (faceColors && faceColors[f] === undefined) {
  37449. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37450. }
  37451. }
  37452. for (f = 0; f < surfaceNb; f++) {
  37453. if (faceUV && faceUV[f] === undefined) {
  37454. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37455. }
  37456. }
  37457. var indices = new Array();
  37458. var positions = new Array();
  37459. var normals = new Array();
  37460. var uvs = new Array();
  37461. var colors = new Array();
  37462. var angle_step = Math.PI * 2 * arc / tessellation;
  37463. var angle;
  37464. var h;
  37465. var radius;
  37466. var tan = (diameterBottom - diameterTop) / 2 / height;
  37467. var ringVertex = BABYLON.Vector3.Zero();
  37468. var ringNormal = BABYLON.Vector3.Zero();
  37469. var ringFirstVertex = BABYLON.Vector3.Zero();
  37470. var ringFirstNormal = BABYLON.Vector3.Zero();
  37471. var quadNormal = BABYLON.Vector3.Zero();
  37472. var Y = BABYLON.Axis.Y;
  37473. // positions, normals, uvs
  37474. var i;
  37475. var j;
  37476. var r;
  37477. var ringIdx = 1;
  37478. var s = 1; // surface index
  37479. var cs = 0;
  37480. var v = 0;
  37481. for (i = 0; i <= subdivisions; i++) {
  37482. h = i / subdivisions;
  37483. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37484. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37485. for (r = 0; r < ringIdx; r++) {
  37486. if (hasRings) {
  37487. s += r;
  37488. }
  37489. if (enclose) {
  37490. s += 2 * r;
  37491. }
  37492. for (j = 0; j <= tessellation; j++) {
  37493. angle = j * angle_step;
  37494. // position
  37495. ringVertex.x = Math.cos(-angle) * radius;
  37496. ringVertex.y = -height / 2 + h * height;
  37497. ringVertex.z = Math.sin(-angle) * radius;
  37498. // normal
  37499. if (diameterTop === 0 && i === subdivisions) {
  37500. // if no top cap, reuse former normals
  37501. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37502. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37503. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37504. }
  37505. else {
  37506. ringNormal.x = ringVertex.x;
  37507. ringNormal.z = ringVertex.z;
  37508. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37509. ringNormal.normalize();
  37510. }
  37511. // keep first ring vertex values for enclose
  37512. if (j === 0) {
  37513. ringFirstVertex.copyFrom(ringVertex);
  37514. ringFirstNormal.copyFrom(ringNormal);
  37515. }
  37516. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37517. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37518. if (hasRings) {
  37519. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37520. }
  37521. else {
  37522. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37523. }
  37524. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37525. if (faceColors) {
  37526. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37527. }
  37528. }
  37529. // if enclose, add four vertices and their dedicated normals
  37530. if (arc !== 1 && enclose) {
  37531. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37532. positions.push(0, ringVertex.y, 0);
  37533. positions.push(0, ringVertex.y, 0);
  37534. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37535. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37536. quadNormal.normalize();
  37537. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37538. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37539. quadNormal.normalize();
  37540. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37541. if (hasRings) {
  37542. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37543. }
  37544. else {
  37545. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37546. }
  37547. uvs.push(faceUV[s + 1].x, v);
  37548. uvs.push(faceUV[s + 1].z, v);
  37549. if (hasRings) {
  37550. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37551. }
  37552. else {
  37553. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37554. }
  37555. uvs.push(faceUV[s + 2].x, v);
  37556. uvs.push(faceUV[s + 2].z, v);
  37557. if (faceColors) {
  37558. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37559. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37560. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37561. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37562. }
  37563. }
  37564. if (cs !== s) {
  37565. cs = s;
  37566. }
  37567. }
  37568. }
  37569. // indices
  37570. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37571. var s;
  37572. i = 0;
  37573. for (s = 0; s < subdivisions; s++) {
  37574. var i0 = 0;
  37575. var i1 = 0;
  37576. var i2 = 0;
  37577. var i3 = 0;
  37578. for (j = 0; j < tessellation; j++) {
  37579. i0 = i * (e + 1) + j;
  37580. i1 = (i + 1) * (e + 1) + j;
  37581. i2 = i * (e + 1) + (j + 1);
  37582. i3 = (i + 1) * (e + 1) + (j + 1);
  37583. indices.push(i0, i1, i2);
  37584. indices.push(i3, i2, i1);
  37585. }
  37586. if (arc !== 1 && enclose) { // if enclose, add two quads
  37587. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37588. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37589. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37590. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37591. }
  37592. i = (hasRings) ? (i + 2) : (i + 1);
  37593. }
  37594. // Caps
  37595. var createCylinderCap = function (isTop) {
  37596. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37597. if (radius === 0) {
  37598. return;
  37599. }
  37600. // Cap positions, normals & uvs
  37601. var angle;
  37602. var circleVector;
  37603. var i;
  37604. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37605. var c = null;
  37606. if (faceColors) {
  37607. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37608. }
  37609. // cap center
  37610. var vbase = positions.length / 3;
  37611. var offset = isTop ? height / 2 : -height / 2;
  37612. var center = new BABYLON.Vector3(0, offset, 0);
  37613. positions.push(center.x, center.y, center.z);
  37614. normals.push(0, isTop ? 1 : -1, 0);
  37615. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37616. if (c) {
  37617. colors.push(c.r, c.g, c.b, c.a);
  37618. }
  37619. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37620. for (i = 0; i <= tessellation; i++) {
  37621. angle = Math.PI * 2 * i * arc / tessellation;
  37622. var cos = Math.cos(-angle);
  37623. var sin = Math.sin(-angle);
  37624. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37625. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37626. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37627. normals.push(0, isTop ? 1 : -1, 0);
  37628. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37629. if (c) {
  37630. colors.push(c.r, c.g, c.b, c.a);
  37631. }
  37632. }
  37633. // Cap indices
  37634. for (i = 0; i < tessellation; i++) {
  37635. if (!isTop) {
  37636. indices.push(vbase);
  37637. indices.push(vbase + (i + 1));
  37638. indices.push(vbase + (i + 2));
  37639. }
  37640. else {
  37641. indices.push(vbase);
  37642. indices.push(vbase + (i + 2));
  37643. indices.push(vbase + (i + 1));
  37644. }
  37645. }
  37646. };
  37647. // add caps to geometry
  37648. createCylinderCap(false);
  37649. createCylinderCap(true);
  37650. // Sides
  37651. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37652. var vertexData = new VertexData();
  37653. vertexData.indices = indices;
  37654. vertexData.positions = positions;
  37655. vertexData.normals = normals;
  37656. vertexData.uvs = uvs;
  37657. if (faceColors) {
  37658. vertexData.colors = colors;
  37659. }
  37660. return vertexData;
  37661. };
  37662. /**
  37663. * Creates the VertexData for a torus
  37664. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37665. * * diameter the diameter of the torus, optional default 1
  37666. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37667. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37668. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37669. * * 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)
  37670. * * 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)
  37671. * @returns the VertexData of the torus
  37672. */
  37673. VertexData.CreateTorus = function (options) {
  37674. var indices = [];
  37675. var positions = [];
  37676. var normals = [];
  37677. var uvs = [];
  37678. var diameter = options.diameter || 1;
  37679. var thickness = options.thickness || 0.5;
  37680. var tessellation = options.tessellation || 16;
  37681. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37682. var stride = tessellation + 1;
  37683. for (var i = 0; i <= tessellation; i++) {
  37684. var u = i / tessellation;
  37685. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37686. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37687. for (var j = 0; j <= tessellation; j++) {
  37688. var v = 1 - j / tessellation;
  37689. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37690. var dx = Math.cos(innerAngle);
  37691. var dy = Math.sin(innerAngle);
  37692. // Create a vertex.
  37693. var normal = new BABYLON.Vector3(dx, dy, 0);
  37694. var position = normal.scale(thickness / 2);
  37695. var textureCoordinate = new BABYLON.Vector2(u, v);
  37696. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37697. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37698. positions.push(position.x, position.y, position.z);
  37699. normals.push(normal.x, normal.y, normal.z);
  37700. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37701. // And create indices for two triangles.
  37702. var nextI = (i + 1) % stride;
  37703. var nextJ = (j + 1) % stride;
  37704. indices.push(i * stride + j);
  37705. indices.push(i * stride + nextJ);
  37706. indices.push(nextI * stride + j);
  37707. indices.push(i * stride + nextJ);
  37708. indices.push(nextI * stride + nextJ);
  37709. indices.push(nextI * stride + j);
  37710. }
  37711. }
  37712. // Sides
  37713. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37714. // Result
  37715. var vertexData = new VertexData();
  37716. vertexData.indices = indices;
  37717. vertexData.positions = positions;
  37718. vertexData.normals = normals;
  37719. vertexData.uvs = uvs;
  37720. return vertexData;
  37721. };
  37722. /**
  37723. * Creates the VertexData of the LineSystem
  37724. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37725. * - lines an array of lines, each line being an array of successive Vector3
  37726. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37727. * @returns the VertexData of the LineSystem
  37728. */
  37729. VertexData.CreateLineSystem = function (options) {
  37730. var indices = [];
  37731. var positions = [];
  37732. var lines = options.lines;
  37733. var colors = options.colors;
  37734. var vertexColors = [];
  37735. var idx = 0;
  37736. for (var l = 0; l < lines.length; l++) {
  37737. var points = lines[l];
  37738. for (var index = 0; index < points.length; index++) {
  37739. positions.push(points[index].x, points[index].y, points[index].z);
  37740. if (colors) {
  37741. var color = colors[l];
  37742. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37743. }
  37744. if (index > 0) {
  37745. indices.push(idx - 1);
  37746. indices.push(idx);
  37747. }
  37748. idx++;
  37749. }
  37750. }
  37751. var vertexData = new VertexData();
  37752. vertexData.indices = indices;
  37753. vertexData.positions = positions;
  37754. if (colors) {
  37755. vertexData.colors = vertexColors;
  37756. }
  37757. return vertexData;
  37758. };
  37759. /**
  37760. * Create the VertexData for a DashedLines
  37761. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37762. * - points an array successive Vector3
  37763. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37764. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37765. * - dashNb the intended total number of dashes, optional, default 200
  37766. * @returns the VertexData for the DashedLines
  37767. */
  37768. VertexData.CreateDashedLines = function (options) {
  37769. var dashSize = options.dashSize || 3;
  37770. var gapSize = options.gapSize || 1;
  37771. var dashNb = options.dashNb || 200;
  37772. var points = options.points;
  37773. var positions = new Array();
  37774. var indices = new Array();
  37775. var curvect = BABYLON.Vector3.Zero();
  37776. var lg = 0;
  37777. var nb = 0;
  37778. var shft = 0;
  37779. var dashshft = 0;
  37780. var curshft = 0;
  37781. var idx = 0;
  37782. var i = 0;
  37783. for (i = 0; i < points.length - 1; i++) {
  37784. points[i + 1].subtractToRef(points[i], curvect);
  37785. lg += curvect.length();
  37786. }
  37787. shft = lg / dashNb;
  37788. dashshft = dashSize * shft / (dashSize + gapSize);
  37789. for (i = 0; i < points.length - 1; i++) {
  37790. points[i + 1].subtractToRef(points[i], curvect);
  37791. nb = Math.floor(curvect.length() / shft);
  37792. curvect.normalize();
  37793. for (var j = 0; j < nb; j++) {
  37794. curshft = shft * j;
  37795. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37796. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37797. indices.push(idx, idx + 1);
  37798. idx += 2;
  37799. }
  37800. }
  37801. // Result
  37802. var vertexData = new VertexData();
  37803. vertexData.positions = positions;
  37804. vertexData.indices = indices;
  37805. return vertexData;
  37806. };
  37807. /**
  37808. * Creates the VertexData for a Ground
  37809. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37810. * - width the width (x direction) of the ground, optional, default 1
  37811. * - height the height (z direction) of the ground, optional, default 1
  37812. * - subdivisions the number of subdivisions per side, optional, default 1
  37813. * @returns the VertexData of the Ground
  37814. */
  37815. VertexData.CreateGround = function (options) {
  37816. var indices = [];
  37817. var positions = [];
  37818. var normals = [];
  37819. var uvs = [];
  37820. var row, col;
  37821. var width = options.width || 1;
  37822. var height = options.height || 1;
  37823. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37824. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37825. for (row = 0; row <= subdivisionsY; row++) {
  37826. for (col = 0; col <= subdivisionsX; col++) {
  37827. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37828. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37829. positions.push(position.x, position.y, position.z);
  37830. normals.push(normal.x, normal.y, normal.z);
  37831. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37832. }
  37833. }
  37834. for (row = 0; row < subdivisionsY; row++) {
  37835. for (col = 0; col < subdivisionsX; col++) {
  37836. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37837. indices.push(col + 1 + row * (subdivisionsX + 1));
  37838. indices.push(col + row * (subdivisionsX + 1));
  37839. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37840. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37841. indices.push(col + row * (subdivisionsX + 1));
  37842. }
  37843. }
  37844. // Result
  37845. var vertexData = new VertexData();
  37846. vertexData.indices = indices;
  37847. vertexData.positions = positions;
  37848. vertexData.normals = normals;
  37849. vertexData.uvs = uvs;
  37850. return vertexData;
  37851. };
  37852. /**
  37853. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37854. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37855. * * xmin the ground minimum X coordinate, optional, default -1
  37856. * * zmin the ground minimum Z coordinate, optional, default -1
  37857. * * xmax the ground maximum X coordinate, optional, default 1
  37858. * * zmax the ground maximum Z coordinate, optional, default 1
  37859. * * 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}
  37860. * * 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}
  37861. * @returns the VertexData of the TiledGround
  37862. */
  37863. VertexData.CreateTiledGround = function (options) {
  37864. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37865. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37866. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37867. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37868. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37869. var precision = options.precision || { w: 1, h: 1 };
  37870. var indices = new Array();
  37871. var positions = new Array();
  37872. var normals = new Array();
  37873. var uvs = new Array();
  37874. var row, col, tileRow, tileCol;
  37875. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37876. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37877. precision.w = (precision.w < 1) ? 1 : precision.w;
  37878. precision.h = (precision.h < 1) ? 1 : precision.h;
  37879. var tileSize = {
  37880. 'w': (xmax - xmin) / subdivisions.w,
  37881. 'h': (zmax - zmin) / subdivisions.h
  37882. };
  37883. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37884. // Indices
  37885. var base = positions.length / 3;
  37886. var rowLength = precision.w + 1;
  37887. for (row = 0; row < precision.h; row++) {
  37888. for (col = 0; col < precision.w; col++) {
  37889. var square = [
  37890. base + col + row * rowLength,
  37891. base + (col + 1) + row * rowLength,
  37892. base + (col + 1) + (row + 1) * rowLength,
  37893. base + col + (row + 1) * rowLength
  37894. ];
  37895. indices.push(square[1]);
  37896. indices.push(square[2]);
  37897. indices.push(square[3]);
  37898. indices.push(square[0]);
  37899. indices.push(square[1]);
  37900. indices.push(square[3]);
  37901. }
  37902. }
  37903. // Position, normals and uvs
  37904. var position = BABYLON.Vector3.Zero();
  37905. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37906. for (row = 0; row <= precision.h; row++) {
  37907. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37908. for (col = 0; col <= precision.w; col++) {
  37909. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37910. position.y = 0;
  37911. positions.push(position.x, position.y, position.z);
  37912. normals.push(normal.x, normal.y, normal.z);
  37913. uvs.push(col / precision.w, row / precision.h);
  37914. }
  37915. }
  37916. }
  37917. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37918. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37919. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37920. }
  37921. }
  37922. // Result
  37923. var vertexData = new VertexData();
  37924. vertexData.indices = indices;
  37925. vertexData.positions = positions;
  37926. vertexData.normals = normals;
  37927. vertexData.uvs = uvs;
  37928. return vertexData;
  37929. };
  37930. /**
  37931. * Creates the VertexData of the Ground designed from a heightmap
  37932. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37933. * * width the width (x direction) of the ground
  37934. * * height the height (z direction) of the ground
  37935. * * subdivisions the number of subdivisions per side
  37936. * * minHeight the minimum altitude on the ground, optional, default 0
  37937. * * maxHeight the maximum altitude on the ground, optional default 1
  37938. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37939. * * buffer the array holding the image color data
  37940. * * bufferWidth the width of image
  37941. * * bufferHeight the height of image
  37942. * @returns the VertexData of the Ground designed from a heightmap
  37943. */
  37944. VertexData.CreateGroundFromHeightMap = function (options) {
  37945. var indices = [];
  37946. var positions = [];
  37947. var normals = [];
  37948. var uvs = [];
  37949. var row, col;
  37950. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37951. // Vertices
  37952. for (row = 0; row <= options.subdivisions; row++) {
  37953. for (col = 0; col <= options.subdivisions; col++) {
  37954. 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));
  37955. // Compute height
  37956. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37957. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37958. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37959. var r = options.buffer[pos] / 255.0;
  37960. var g = options.buffer[pos + 1] / 255.0;
  37961. var b = options.buffer[pos + 2] / 255.0;
  37962. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37963. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37964. // Add vertex
  37965. positions.push(position.x, position.y, position.z);
  37966. normals.push(0, 0, 0);
  37967. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37968. }
  37969. }
  37970. // Indices
  37971. for (row = 0; row < options.subdivisions; row++) {
  37972. for (col = 0; col < options.subdivisions; col++) {
  37973. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37974. indices.push(col + 1 + row * (options.subdivisions + 1));
  37975. indices.push(col + row * (options.subdivisions + 1));
  37976. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37977. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37978. indices.push(col + row * (options.subdivisions + 1));
  37979. }
  37980. }
  37981. // Normals
  37982. VertexData.ComputeNormals(positions, indices, normals);
  37983. // Result
  37984. var vertexData = new VertexData();
  37985. vertexData.indices = indices;
  37986. vertexData.positions = positions;
  37987. vertexData.normals = normals;
  37988. vertexData.uvs = uvs;
  37989. return vertexData;
  37990. };
  37991. /**
  37992. * Creates the VertexData for a Plane
  37993. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37994. * * size sets the width and height of the plane to the value of size, optional default 1
  37995. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37996. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37997. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37998. * * 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)
  37999. * * 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)
  38000. * @returns the VertexData of the box
  38001. */
  38002. VertexData.CreatePlane = function (options) {
  38003. var indices = [];
  38004. var positions = [];
  38005. var normals = [];
  38006. var uvs = [];
  38007. var width = options.width || options.size || 1;
  38008. var height = options.height || options.size || 1;
  38009. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38010. // Vertices
  38011. var halfWidth = width / 2.0;
  38012. var halfHeight = height / 2.0;
  38013. positions.push(-halfWidth, -halfHeight, 0);
  38014. normals.push(0, 0, -1.0);
  38015. uvs.push(0.0, 0.0);
  38016. positions.push(halfWidth, -halfHeight, 0);
  38017. normals.push(0, 0, -1.0);
  38018. uvs.push(1.0, 0.0);
  38019. positions.push(halfWidth, halfHeight, 0);
  38020. normals.push(0, 0, -1.0);
  38021. uvs.push(1.0, 1.0);
  38022. positions.push(-halfWidth, halfHeight, 0);
  38023. normals.push(0, 0, -1.0);
  38024. uvs.push(0.0, 1.0);
  38025. // Indices
  38026. indices.push(0);
  38027. indices.push(1);
  38028. indices.push(2);
  38029. indices.push(0);
  38030. indices.push(2);
  38031. indices.push(3);
  38032. // Sides
  38033. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38034. // Result
  38035. var vertexData = new VertexData();
  38036. vertexData.indices = indices;
  38037. vertexData.positions = positions;
  38038. vertexData.normals = normals;
  38039. vertexData.uvs = uvs;
  38040. return vertexData;
  38041. };
  38042. /**
  38043. * Creates the VertexData of the Disc or regular Polygon
  38044. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38045. * * radius the radius of the disc, optional default 0.5
  38046. * * tessellation the number of polygon sides, optional, default 64
  38047. * * 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
  38048. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38049. * * 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)
  38050. * * 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)
  38051. * @returns the VertexData of the box
  38052. */
  38053. VertexData.CreateDisc = function (options) {
  38054. var positions = new Array();
  38055. var indices = new Array();
  38056. var normals = new Array();
  38057. var uvs = new Array();
  38058. var radius = options.radius || 0.5;
  38059. var tessellation = options.tessellation || 64;
  38060. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38061. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38062. // positions and uvs
  38063. positions.push(0, 0, 0); // disc center first
  38064. uvs.push(0.5, 0.5);
  38065. var theta = Math.PI * 2 * arc;
  38066. var step = theta / tessellation;
  38067. for (var a = 0; a < theta; a += step) {
  38068. var x = Math.cos(a);
  38069. var y = Math.sin(a);
  38070. var u = (x + 1) / 2;
  38071. var v = (1 - y) / 2;
  38072. positions.push(radius * x, radius * y, 0);
  38073. uvs.push(u, v);
  38074. }
  38075. if (arc === 1) {
  38076. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38077. uvs.push(uvs[2], uvs[3]);
  38078. }
  38079. //indices
  38080. var vertexNb = positions.length / 3;
  38081. for (var i = 1; i < vertexNb - 1; i++) {
  38082. indices.push(i + 1, 0, i);
  38083. }
  38084. // result
  38085. VertexData.ComputeNormals(positions, indices, normals);
  38086. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38087. var vertexData = new VertexData();
  38088. vertexData.indices = indices;
  38089. vertexData.positions = positions;
  38090. vertexData.normals = normals;
  38091. vertexData.uvs = uvs;
  38092. return vertexData;
  38093. };
  38094. /**
  38095. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38096. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38097. * @param polygon a mesh built from polygonTriangulation.build()
  38098. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38099. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38100. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38101. * @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)
  38102. * @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)
  38103. * @returns the VertexData of the Polygon
  38104. */
  38105. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38106. var faceUV = fUV || new Array(3);
  38107. var faceColors = fColors;
  38108. var colors = [];
  38109. // default face colors and UV if undefined
  38110. for (var f = 0; f < 3; f++) {
  38111. if (faceUV[f] === undefined) {
  38112. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38113. }
  38114. if (faceColors && faceColors[f] === undefined) {
  38115. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38116. }
  38117. }
  38118. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38119. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38120. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38121. var indices = polygon.getIndices();
  38122. // set face colours and textures
  38123. var idx = 0;
  38124. var face = 0;
  38125. for (var index = 0; index < normals.length; index += 3) {
  38126. //Edge Face no. 1
  38127. if (Math.abs(normals[index + 1]) < 0.001) {
  38128. face = 1;
  38129. }
  38130. //Top Face no. 0
  38131. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38132. face = 0;
  38133. }
  38134. //Bottom Face no. 2
  38135. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38136. face = 2;
  38137. }
  38138. idx = index / 3;
  38139. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38140. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38141. if (faceColors) {
  38142. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38143. }
  38144. }
  38145. // sides
  38146. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38147. // Result
  38148. var vertexData = new VertexData();
  38149. vertexData.indices = indices;
  38150. vertexData.positions = positions;
  38151. vertexData.normals = normals;
  38152. vertexData.uvs = uvs;
  38153. if (faceColors) {
  38154. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38155. vertexData.colors = totalColors;
  38156. }
  38157. return vertexData;
  38158. };
  38159. /**
  38160. * Creates the VertexData of the IcoSphere
  38161. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38162. * * radius the radius of the IcoSphere, optional default 1
  38163. * * radiusX allows stretching in the x direction, optional, default radius
  38164. * * radiusY allows stretching in the y direction, optional, default radius
  38165. * * radiusZ allows stretching in the z direction, optional, default radius
  38166. * * flat when true creates a flat shaded mesh, optional, default true
  38167. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38168. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38169. * * 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)
  38170. * * 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)
  38171. * @returns the VertexData of the IcoSphere
  38172. */
  38173. VertexData.CreateIcoSphere = function (options) {
  38174. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38175. var radius = options.radius || 1;
  38176. var flat = (options.flat === undefined) ? true : options.flat;
  38177. var subdivisions = options.subdivisions || 4;
  38178. var radiusX = options.radiusX || radius;
  38179. var radiusY = options.radiusY || radius;
  38180. var radiusZ = options.radiusZ || radius;
  38181. var t = (1 + Math.sqrt(5)) / 2;
  38182. // 12 vertex x,y,z
  38183. var ico_vertices = [
  38184. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38185. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38186. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38187. ];
  38188. // index of 3 vertex makes a face of icopshere
  38189. var ico_indices = [
  38190. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38191. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38192. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38193. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38194. ];
  38195. // vertex for uv have aliased position, not for UV
  38196. var vertices_unalias_id = [
  38197. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38198. // vertex alias
  38199. 0,
  38200. 2,
  38201. 3,
  38202. 3,
  38203. 3,
  38204. 4,
  38205. 7,
  38206. 8,
  38207. 9,
  38208. 9,
  38209. 10,
  38210. 11 // 23: B + 12
  38211. ];
  38212. // uv as integer step (not pixels !)
  38213. var ico_vertexuv = [
  38214. 5, 1, 3, 1, 6, 4, 0, 0,
  38215. 5, 3, 4, 2, 2, 2, 4, 0,
  38216. 2, 0, 1, 1, 6, 0, 6, 2,
  38217. // vertex alias (for same vertex on different faces)
  38218. 0, 4,
  38219. 3, 3,
  38220. 4, 4,
  38221. 3, 1,
  38222. 4, 2,
  38223. 4, 4,
  38224. 0, 2,
  38225. 1, 1,
  38226. 2, 2,
  38227. 3, 3,
  38228. 1, 3,
  38229. 2, 4 // 23: B + 12
  38230. ];
  38231. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38232. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38233. // First island of uv mapping
  38234. // v = 4h 3+ 2
  38235. // v = 3h 9+ 4
  38236. // v = 2h 9+ 5 B
  38237. // v = 1h 9 1 0
  38238. // v = 0h 3 8 7 A
  38239. // u = 0 1 2 3 4 5 6 *a
  38240. // Second island of uv mapping
  38241. // v = 4h 0+ B+ 4+
  38242. // v = 3h A+ 2+
  38243. // v = 2h 7+ 6 3+
  38244. // v = 1h 8+ 3+
  38245. // v = 0h
  38246. // u = 0 1 2 3 4 5 6 *a
  38247. // Face layout on texture UV mapping
  38248. // ============
  38249. // \ 4 /\ 16 / ======
  38250. // \ / \ / /\ 11 /
  38251. // \/ 7 \/ / \ /
  38252. // ======= / 10 \/
  38253. // /\ 17 /\ =======
  38254. // / \ / \ \ 15 /\
  38255. // / 8 \/ 12 \ \ / \
  38256. // ============ \/ 6 \
  38257. // \ 18 /\ ============
  38258. // \ / \ \ 5 /\ 0 /
  38259. // \/ 13 \ \ / \ /
  38260. // ======= \/ 1 \/
  38261. // =============
  38262. // /\ 19 /\ 2 /\
  38263. // / \ / \ / \
  38264. // / 14 \/ 9 \/ 3 \
  38265. // ===================
  38266. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38267. var ustep = 138 / 1024;
  38268. var vstep = 239 / 1024;
  38269. var uoffset = 60 / 1024;
  38270. var voffset = 26 / 1024;
  38271. // Second island should have margin, not to touch the first island
  38272. // avoid any borderline artefact in pixel rounding
  38273. var island_u_offset = -40 / 1024;
  38274. var island_v_offset = +20 / 1024;
  38275. // face is either island 0 or 1 :
  38276. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38277. var island = [
  38278. 0, 0, 0, 0, 1,
  38279. 0, 0, 1, 1, 0,
  38280. 0, 0, 1, 1, 0,
  38281. 0, 1, 1, 1, 0 // 15 - 19
  38282. ];
  38283. var indices = new Array();
  38284. var positions = new Array();
  38285. var normals = new Array();
  38286. var uvs = new Array();
  38287. var current_indice = 0;
  38288. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38289. var face_vertex_pos = new Array(3);
  38290. var face_vertex_uv = new Array(3);
  38291. var v012;
  38292. for (v012 = 0; v012 < 3; v012++) {
  38293. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38294. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38295. }
  38296. // create all with normals
  38297. for (var face = 0; face < 20; face++) {
  38298. // 3 vertex per face
  38299. for (v012 = 0; v012 < 3; v012++) {
  38300. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38301. var v_id = ico_indices[3 * face + v012];
  38302. // vertex have 3D position (x,y,z)
  38303. 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]);
  38304. // Normalize to get normal, then scale to radius
  38305. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38306. // uv Coordinates from vertex ID
  38307. 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);
  38308. }
  38309. // Subdivide the face (interpolate pos, norm, uv)
  38310. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38311. // - norm is linear interpolation of vertex corner normal
  38312. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38313. // - uv is linear interpolation
  38314. //
  38315. // Topology is as below for sub-divide by 2
  38316. // vertex shown as v0,v1,v2
  38317. // interp index is i1 to progress in range [v0,v1[
  38318. // interp index is i2 to progress in range [v0,v2[
  38319. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38320. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38321. //
  38322. //
  38323. // i2 v2
  38324. // ^ ^
  38325. // / / \
  38326. // / / \
  38327. // / / \
  38328. // / / (0,1) \
  38329. // / #---------\
  38330. // / / \ (0,0)'/ \
  38331. // / / \ / \
  38332. // / / \ / \
  38333. // / / (0,0) \ / (1,0) \
  38334. // / #---------#---------\
  38335. // v0 v1
  38336. //
  38337. // --------------------> i1
  38338. //
  38339. // interp of (i1,i2):
  38340. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38341. // along i1 : lerp(x0,x1, i1/(S-i2))
  38342. //
  38343. // centroid of triangle is needed to get help normal computation
  38344. // (c1,c2) are used for centroid location
  38345. var interp_vertex = function (i1, i2, c1, c2) {
  38346. // vertex is interpolated from
  38347. // - face_vertex_pos[0..2]
  38348. // - face_vertex_uv[0..2]
  38349. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38350. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38351. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38352. pos_interp.normalize();
  38353. var vertex_normal;
  38354. if (flat) {
  38355. // in flat mode, recalculate normal as face centroid normal
  38356. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38357. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38358. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38359. }
  38360. else {
  38361. // in smooth mode, recalculate normal from each single vertex position
  38362. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38363. }
  38364. // Vertex normal need correction due to X,Y,Z radius scaling
  38365. vertex_normal.x /= radiusX;
  38366. vertex_normal.y /= radiusY;
  38367. vertex_normal.z /= radiusZ;
  38368. vertex_normal.normalize();
  38369. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38370. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38371. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38372. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38373. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38374. uvs.push(uv_interp.x, uv_interp.y);
  38375. // push each vertex has member of a face
  38376. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38377. indices.push(current_indice);
  38378. current_indice++;
  38379. };
  38380. for (var i2 = 0; i2 < subdivisions; i2++) {
  38381. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38382. // face : (i1,i2) for /\ :
  38383. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38384. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38385. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38386. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38387. if (i1 + i2 + 1 < subdivisions) {
  38388. // face : (i1,i2)' for \/ :
  38389. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38390. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38391. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38392. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38393. }
  38394. }
  38395. }
  38396. }
  38397. // Sides
  38398. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38399. // Result
  38400. var vertexData = new VertexData();
  38401. vertexData.indices = indices;
  38402. vertexData.positions = positions;
  38403. vertexData.normals = normals;
  38404. vertexData.uvs = uvs;
  38405. return vertexData;
  38406. };
  38407. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38408. /**
  38409. * Creates the VertexData for a Polyhedron
  38410. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38411. * * type provided types are:
  38412. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38413. * * 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)
  38414. * * size the size of the IcoSphere, optional default 1
  38415. * * sizeX allows stretching in the x direction, optional, default size
  38416. * * sizeY allows stretching in the y direction, optional, default size
  38417. * * sizeZ allows stretching in the z direction, optional, default size
  38418. * * 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
  38419. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38420. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38421. * * flat when true creates a flat shaded mesh, optional, default true
  38422. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38423. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38424. * * 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)
  38425. * * 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)
  38426. * @returns the VertexData of the Polyhedron
  38427. */
  38428. VertexData.CreatePolyhedron = function (options) {
  38429. // provided polyhedron types :
  38430. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38431. // 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)
  38432. var polyhedra = [];
  38433. 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]] };
  38434. 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]] };
  38435. polyhedra[2] = {
  38436. 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]],
  38437. 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]]
  38438. };
  38439. polyhedra[3] = {
  38440. 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]],
  38441. 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]]
  38442. };
  38443. polyhedra[4] = {
  38444. 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]],
  38445. 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]]
  38446. };
  38447. 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]] };
  38448. 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]] };
  38449. 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]] };
  38450. 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]] };
  38451. 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]] };
  38452. 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]] };
  38453. 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]] };
  38454. 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]] };
  38455. 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]] };
  38456. polyhedra[14] = {
  38457. 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]],
  38458. 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]]
  38459. };
  38460. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38461. var size = options.size;
  38462. var sizeX = options.sizeX || size || 1;
  38463. var sizeY = options.sizeY || size || 1;
  38464. var sizeZ = options.sizeZ || size || 1;
  38465. var data = options.custom || polyhedra[type];
  38466. var nbfaces = data.face.length;
  38467. var faceUV = options.faceUV || new Array(nbfaces);
  38468. var faceColors = options.faceColors;
  38469. var flat = (options.flat === undefined) ? true : options.flat;
  38470. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38471. var positions = new Array();
  38472. var indices = new Array();
  38473. var normals = new Array();
  38474. var uvs = new Array();
  38475. var colors = new Array();
  38476. var index = 0;
  38477. var faceIdx = 0; // face cursor in the array "indexes"
  38478. var indexes = new Array();
  38479. var i = 0;
  38480. var f = 0;
  38481. var u, v, ang, x, y, tmp;
  38482. // default face colors and UV if undefined
  38483. if (flat) {
  38484. for (f = 0; f < nbfaces; f++) {
  38485. if (faceColors && faceColors[f] === undefined) {
  38486. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38487. }
  38488. if (faceUV && faceUV[f] === undefined) {
  38489. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38490. }
  38491. }
  38492. }
  38493. if (!flat) {
  38494. for (i = 0; i < data.vertex.length; i++) {
  38495. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38496. uvs.push(0, 0);
  38497. }
  38498. for (f = 0; f < nbfaces; f++) {
  38499. for (i = 0; i < data.face[f].length - 2; i++) {
  38500. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38501. }
  38502. }
  38503. }
  38504. else {
  38505. for (f = 0; f < nbfaces; f++) {
  38506. var fl = data.face[f].length; // number of vertices of the current face
  38507. ang = 2 * Math.PI / fl;
  38508. x = 0.5 * Math.tan(ang / 2);
  38509. y = 0.5;
  38510. // positions, uvs, colors
  38511. for (i = 0; i < fl; i++) {
  38512. // positions
  38513. 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);
  38514. indexes.push(index);
  38515. index++;
  38516. // uvs
  38517. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38518. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38519. uvs.push(u, v);
  38520. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38521. y = x * Math.sin(ang) + y * Math.cos(ang);
  38522. x = tmp;
  38523. // colors
  38524. if (faceColors) {
  38525. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38526. }
  38527. }
  38528. // indices from indexes
  38529. for (i = 0; i < fl - 2; i++) {
  38530. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38531. }
  38532. faceIdx += fl;
  38533. }
  38534. }
  38535. VertexData.ComputeNormals(positions, indices, normals);
  38536. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38537. var vertexData = new VertexData();
  38538. vertexData.positions = positions;
  38539. vertexData.indices = indices;
  38540. vertexData.normals = normals;
  38541. vertexData.uvs = uvs;
  38542. if (faceColors && flat) {
  38543. vertexData.colors = colors;
  38544. }
  38545. return vertexData;
  38546. };
  38547. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38548. /**
  38549. * Creates the VertexData for a TorusKnot
  38550. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38551. * * radius the radius of the torus knot, optional, default 2
  38552. * * tube the thickness of the tube, optional, default 0.5
  38553. * * radialSegments the number of sides on each tube segments, optional, default 32
  38554. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38555. * * p the number of windings around the z axis, optional, default 2
  38556. * * q the number of windings around the x axis, optional, default 3
  38557. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38558. * * 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)
  38559. * * 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)
  38560. * @returns the VertexData of the Torus Knot
  38561. */
  38562. VertexData.CreateTorusKnot = function (options) {
  38563. var indices = new Array();
  38564. var positions = new Array();
  38565. var normals = new Array();
  38566. var uvs = new Array();
  38567. var radius = options.radius || 2;
  38568. var tube = options.tube || 0.5;
  38569. var radialSegments = options.radialSegments || 32;
  38570. var tubularSegments = options.tubularSegments || 32;
  38571. var p = options.p || 2;
  38572. var q = options.q || 3;
  38573. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38574. // Helper
  38575. var getPos = function (angle) {
  38576. var cu = Math.cos(angle);
  38577. var su = Math.sin(angle);
  38578. var quOverP = q / p * angle;
  38579. var cs = Math.cos(quOverP);
  38580. var tx = radius * (2 + cs) * 0.5 * cu;
  38581. var ty = radius * (2 + cs) * su * 0.5;
  38582. var tz = radius * Math.sin(quOverP) * 0.5;
  38583. return new BABYLON.Vector3(tx, ty, tz);
  38584. };
  38585. // Vertices
  38586. var i;
  38587. var j;
  38588. for (i = 0; i <= radialSegments; i++) {
  38589. var modI = i % radialSegments;
  38590. var u = modI / radialSegments * 2 * p * Math.PI;
  38591. var p1 = getPos(u);
  38592. var p2 = getPos(u + 0.01);
  38593. var tang = p2.subtract(p1);
  38594. var n = p2.add(p1);
  38595. var bitan = BABYLON.Vector3.Cross(tang, n);
  38596. n = BABYLON.Vector3.Cross(bitan, tang);
  38597. bitan.normalize();
  38598. n.normalize();
  38599. for (j = 0; j < tubularSegments; j++) {
  38600. var modJ = j % tubularSegments;
  38601. var v = modJ / tubularSegments * 2 * Math.PI;
  38602. var cx = -tube * Math.cos(v);
  38603. var cy = tube * Math.sin(v);
  38604. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38605. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38606. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38607. uvs.push(i / radialSegments);
  38608. uvs.push(j / tubularSegments);
  38609. }
  38610. }
  38611. for (i = 0; i < radialSegments; i++) {
  38612. for (j = 0; j < tubularSegments; j++) {
  38613. var jNext = (j + 1) % tubularSegments;
  38614. var a = i * tubularSegments + j;
  38615. var b = (i + 1) * tubularSegments + j;
  38616. var c = (i + 1) * tubularSegments + jNext;
  38617. var d = i * tubularSegments + jNext;
  38618. indices.push(d);
  38619. indices.push(b);
  38620. indices.push(a);
  38621. indices.push(d);
  38622. indices.push(c);
  38623. indices.push(b);
  38624. }
  38625. }
  38626. // Normals
  38627. VertexData.ComputeNormals(positions, indices, normals);
  38628. // Sides
  38629. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38630. // Result
  38631. var vertexData = new VertexData();
  38632. vertexData.indices = indices;
  38633. vertexData.positions = positions;
  38634. vertexData.normals = normals;
  38635. vertexData.uvs = uvs;
  38636. return vertexData;
  38637. };
  38638. // Tools
  38639. /**
  38640. * Compute normals for given positions and indices
  38641. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38642. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38643. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38644. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38645. * * facetNormals : optional array of facet normals (vector3)
  38646. * * facetPositions : optional array of facet positions (vector3)
  38647. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38648. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38649. * * bInfo : optional bounding info, required for facetPartitioning computation
  38650. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38651. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38652. * * useRightHandedSystem: optional boolean to for right handed system computation
  38653. * * depthSort : optional boolean to enable the facet depth sort computation
  38654. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38655. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38656. */
  38657. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38658. // temporary scalar variables
  38659. var index = 0; // facet index
  38660. var p1p2x = 0.0; // p1p2 vector x coordinate
  38661. var p1p2y = 0.0; // p1p2 vector y coordinate
  38662. var p1p2z = 0.0; // p1p2 vector z coordinate
  38663. var p3p2x = 0.0; // p3p2 vector x coordinate
  38664. var p3p2y = 0.0; // p3p2 vector y coordinate
  38665. var p3p2z = 0.0; // p3p2 vector z coordinate
  38666. var faceNormalx = 0.0; // facet normal x coordinate
  38667. var faceNormaly = 0.0; // facet normal y coordinate
  38668. var faceNormalz = 0.0; // facet normal z coordinate
  38669. var length = 0.0; // facet normal length before normalization
  38670. var v1x = 0; // vector1 x index in the positions array
  38671. var v1y = 0; // vector1 y index in the positions array
  38672. var v1z = 0; // vector1 z index in the positions array
  38673. var v2x = 0; // vector2 x index in the positions array
  38674. var v2y = 0; // vector2 y index in the positions array
  38675. var v2z = 0; // vector2 z index in the positions array
  38676. var v3x = 0; // vector3 x index in the positions array
  38677. var v3y = 0; // vector3 y index in the positions array
  38678. var v3z = 0; // vector3 z index in the positions array
  38679. var computeFacetNormals = false;
  38680. var computeFacetPositions = false;
  38681. var computeFacetPartitioning = false;
  38682. var computeDepthSort = false;
  38683. var faceNormalSign = 1;
  38684. var ratio = 0;
  38685. var distanceTo = null;
  38686. if (options) {
  38687. computeFacetNormals = (options.facetNormals) ? true : false;
  38688. computeFacetPositions = (options.facetPositions) ? true : false;
  38689. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38690. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38691. ratio = options.ratio || 0;
  38692. computeDepthSort = (options.depthSort) ? true : false;
  38693. distanceTo = (options.distanceTo);
  38694. if (computeDepthSort) {
  38695. if (distanceTo === undefined) {
  38696. distanceTo = BABYLON.Vector3.Zero();
  38697. }
  38698. var depthSortedFacets = options.depthSortedFacets;
  38699. }
  38700. }
  38701. // facetPartitioning reinit if needed
  38702. var xSubRatio = 0;
  38703. var ySubRatio = 0;
  38704. var zSubRatio = 0;
  38705. var subSq = 0;
  38706. if (computeFacetPartitioning && options && options.bbSize) {
  38707. var ox = 0; // X partitioning index for facet position
  38708. var oy = 0; // Y partinioning index for facet position
  38709. var oz = 0; // Z partinioning index for facet position
  38710. var b1x = 0; // X partitioning index for facet v1 vertex
  38711. var b1y = 0; // Y partitioning index for facet v1 vertex
  38712. var b1z = 0; // z partitioning index for facet v1 vertex
  38713. var b2x = 0; // X partitioning index for facet v2 vertex
  38714. var b2y = 0; // Y partitioning index for facet v2 vertex
  38715. var b2z = 0; // Z partitioning index for facet v2 vertex
  38716. var b3x = 0; // X partitioning index for facet v3 vertex
  38717. var b3y = 0; // Y partitioning index for facet v3 vertex
  38718. var b3z = 0; // Z partitioning index for facet v3 vertex
  38719. var block_idx_o = 0; // facet barycenter block index
  38720. var block_idx_v1 = 0; // v1 vertex block index
  38721. var block_idx_v2 = 0; // v2 vertex block index
  38722. var block_idx_v3 = 0; // v3 vertex block index
  38723. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38724. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38725. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38726. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38727. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38728. subSq = options.subDiv.max * options.subDiv.max;
  38729. options.facetPartitioning.length = 0;
  38730. }
  38731. // reset the normals
  38732. for (index = 0; index < positions.length; index++) {
  38733. normals[index] = 0.0;
  38734. }
  38735. // Loop : 1 indice triplet = 1 facet
  38736. var nbFaces = (indices.length / 3) | 0;
  38737. for (index = 0; index < nbFaces; index++) {
  38738. // get the indexes of the coordinates of each vertex of the facet
  38739. v1x = indices[index * 3] * 3;
  38740. v1y = v1x + 1;
  38741. v1z = v1x + 2;
  38742. v2x = indices[index * 3 + 1] * 3;
  38743. v2y = v2x + 1;
  38744. v2z = v2x + 2;
  38745. v3x = indices[index * 3 + 2] * 3;
  38746. v3y = v3x + 1;
  38747. v3z = v3x + 2;
  38748. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38749. p1p2y = positions[v1y] - positions[v2y];
  38750. p1p2z = positions[v1z] - positions[v2z];
  38751. p3p2x = positions[v3x] - positions[v2x];
  38752. p3p2y = positions[v3y] - positions[v2y];
  38753. p3p2z = positions[v3z] - positions[v2z];
  38754. // compute the face normal with the cross product
  38755. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38756. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38757. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38758. // normalize this normal and store it in the array facetData
  38759. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38760. length = (length === 0) ? 1.0 : length;
  38761. faceNormalx /= length;
  38762. faceNormaly /= length;
  38763. faceNormalz /= length;
  38764. if (computeFacetNormals && options) {
  38765. options.facetNormals[index].x = faceNormalx;
  38766. options.facetNormals[index].y = faceNormaly;
  38767. options.facetNormals[index].z = faceNormalz;
  38768. }
  38769. if (computeFacetPositions && options) {
  38770. // compute and the facet barycenter coordinates in the array facetPositions
  38771. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38772. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38773. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38774. }
  38775. if (computeFacetPartitioning && options) {
  38776. // store the facet indexes in arrays in the main facetPartitioning array :
  38777. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38778. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38779. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38780. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38781. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38782. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38783. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38784. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38785. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38786. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38787. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38788. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38789. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38790. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38791. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38792. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38793. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38794. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38795. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38796. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38797. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38798. // push each facet index in each block containing the vertex
  38799. options.facetPartitioning[block_idx_v1].push(index);
  38800. if (block_idx_v2 != block_idx_v1) {
  38801. options.facetPartitioning[block_idx_v2].push(index);
  38802. }
  38803. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38804. options.facetPartitioning[block_idx_v3].push(index);
  38805. }
  38806. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38807. options.facetPartitioning[block_idx_o].push(index);
  38808. }
  38809. }
  38810. if (computeDepthSort && options && options.facetPositions) {
  38811. var dsf = depthSortedFacets[index];
  38812. dsf.ind = index * 3;
  38813. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38814. }
  38815. // compute the normals anyway
  38816. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38817. normals[v1y] += faceNormaly;
  38818. normals[v1z] += faceNormalz;
  38819. normals[v2x] += faceNormalx;
  38820. normals[v2y] += faceNormaly;
  38821. normals[v2z] += faceNormalz;
  38822. normals[v3x] += faceNormalx;
  38823. normals[v3y] += faceNormaly;
  38824. normals[v3z] += faceNormalz;
  38825. }
  38826. // last normalization of each normal
  38827. for (index = 0; index < normals.length / 3; index++) {
  38828. faceNormalx = normals[index * 3];
  38829. faceNormaly = normals[index * 3 + 1];
  38830. faceNormalz = normals[index * 3 + 2];
  38831. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38832. length = (length === 0) ? 1.0 : length;
  38833. faceNormalx /= length;
  38834. faceNormaly /= length;
  38835. faceNormalz /= length;
  38836. normals[index * 3] = faceNormalx;
  38837. normals[index * 3 + 1] = faceNormaly;
  38838. normals[index * 3 + 2] = faceNormalz;
  38839. }
  38840. };
  38841. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38842. var li = indices.length;
  38843. var ln = normals.length;
  38844. var i;
  38845. var n;
  38846. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38847. switch (sideOrientation) {
  38848. case BABYLON.Mesh.FRONTSIDE:
  38849. // nothing changed
  38850. break;
  38851. case BABYLON.Mesh.BACKSIDE:
  38852. var tmp;
  38853. // indices
  38854. for (i = 0; i < li; i += 3) {
  38855. tmp = indices[i];
  38856. indices[i] = indices[i + 2];
  38857. indices[i + 2] = tmp;
  38858. }
  38859. // normals
  38860. for (n = 0; n < ln; n++) {
  38861. normals[n] = -normals[n];
  38862. }
  38863. break;
  38864. case BABYLON.Mesh.DOUBLESIDE:
  38865. // positions
  38866. var lp = positions.length;
  38867. var l = lp / 3;
  38868. for (var p = 0; p < lp; p++) {
  38869. positions[lp + p] = positions[p];
  38870. }
  38871. // indices
  38872. for (i = 0; i < li; i += 3) {
  38873. indices[i + li] = indices[i + 2] + l;
  38874. indices[i + 1 + li] = indices[i + 1] + l;
  38875. indices[i + 2 + li] = indices[i] + l;
  38876. }
  38877. // normals
  38878. for (n = 0; n < ln; n++) {
  38879. normals[ln + n] = -normals[n];
  38880. }
  38881. // uvs
  38882. var lu = uvs.length;
  38883. var u = 0;
  38884. for (u = 0; u < lu; u++) {
  38885. uvs[u + lu] = uvs[u];
  38886. }
  38887. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38888. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38889. u = 0;
  38890. for (i = 0; i < lu / 2; i++) {
  38891. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38892. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38893. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38894. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38895. u += 2;
  38896. }
  38897. break;
  38898. }
  38899. };
  38900. /**
  38901. * Applies VertexData created from the imported parameters to the geometry
  38902. * @param parsedVertexData the parsed data from an imported file
  38903. * @param geometry the geometry to apply the VertexData to
  38904. */
  38905. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38906. var vertexData = new VertexData();
  38907. // positions
  38908. var positions = parsedVertexData.positions;
  38909. if (positions) {
  38910. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38911. }
  38912. // normals
  38913. var normals = parsedVertexData.normals;
  38914. if (normals) {
  38915. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38916. }
  38917. // tangents
  38918. var tangents = parsedVertexData.tangents;
  38919. if (tangents) {
  38920. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38921. }
  38922. // uvs
  38923. var uvs = parsedVertexData.uvs;
  38924. if (uvs) {
  38925. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38926. }
  38927. // uv2s
  38928. var uv2s = parsedVertexData.uv2s;
  38929. if (uv2s) {
  38930. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38931. }
  38932. // uv3s
  38933. var uv3s = parsedVertexData.uv3s;
  38934. if (uv3s) {
  38935. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38936. }
  38937. // uv4s
  38938. var uv4s = parsedVertexData.uv4s;
  38939. if (uv4s) {
  38940. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38941. }
  38942. // uv5s
  38943. var uv5s = parsedVertexData.uv5s;
  38944. if (uv5s) {
  38945. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38946. }
  38947. // uv6s
  38948. var uv6s = parsedVertexData.uv6s;
  38949. if (uv6s) {
  38950. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38951. }
  38952. // colors
  38953. var colors = parsedVertexData.colors;
  38954. if (colors) {
  38955. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38956. }
  38957. // matricesIndices
  38958. var matricesIndices = parsedVertexData.matricesIndices;
  38959. if (matricesIndices) {
  38960. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38961. }
  38962. // matricesWeights
  38963. var matricesWeights = parsedVertexData.matricesWeights;
  38964. if (matricesWeights) {
  38965. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38966. }
  38967. // indices
  38968. var indices = parsedVertexData.indices;
  38969. if (indices) {
  38970. vertexData.indices = indices;
  38971. }
  38972. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38973. };
  38974. return VertexData;
  38975. }());
  38976. BABYLON.VertexData = VertexData;
  38977. })(BABYLON || (BABYLON = {}));
  38978. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38979. var BABYLON;
  38980. (function (BABYLON) {
  38981. /**
  38982. * Class used to store geometry data (vertex buffers + index buffer)
  38983. */
  38984. var Geometry = /** @class */ (function () {
  38985. /**
  38986. * Creates a new geometry
  38987. * @param id defines the unique ID
  38988. * @param scene defines the hosting scene
  38989. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38990. * @param updatable defines if geometry must be updatable (false by default)
  38991. * @param mesh defines the mesh that will be associated with the geometry
  38992. */
  38993. function Geometry(id, scene, vertexData, updatable, mesh) {
  38994. if (updatable === void 0) { updatable = false; }
  38995. if (mesh === void 0) { mesh = null; }
  38996. /**
  38997. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38998. */
  38999. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39000. this._totalVertices = 0;
  39001. this._isDisposed = false;
  39002. this._indexBufferIsUpdatable = false;
  39003. this.id = id;
  39004. this._engine = scene.getEngine();
  39005. this._meshes = [];
  39006. this._scene = scene;
  39007. //Init vertex buffer cache
  39008. this._vertexBuffers = {};
  39009. this._indices = [];
  39010. this._updatable = updatable;
  39011. // vertexData
  39012. if (vertexData) {
  39013. this.setAllVerticesData(vertexData, updatable);
  39014. }
  39015. else {
  39016. this._totalVertices = 0;
  39017. this._indices = [];
  39018. }
  39019. if (this._engine.getCaps().vertexArrayObject) {
  39020. this._vertexArrayObjects = {};
  39021. }
  39022. // applyToMesh
  39023. if (mesh) {
  39024. if (mesh.getClassName() === "LinesMesh") {
  39025. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39026. this._updateExtend();
  39027. }
  39028. this.applyToMesh(mesh);
  39029. mesh.computeWorldMatrix(true);
  39030. }
  39031. }
  39032. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39033. /**
  39034. * 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
  39035. */
  39036. get: function () {
  39037. return this._boundingBias;
  39038. },
  39039. /**
  39040. * 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
  39041. */
  39042. set: function (value) {
  39043. if (this._boundingBias && this._boundingBias.equals(value)) {
  39044. return;
  39045. }
  39046. this._boundingBias = value.clone();
  39047. this._updateBoundingInfo(true, null);
  39048. },
  39049. enumerable: true,
  39050. configurable: true
  39051. });
  39052. /**
  39053. * Static function used to attach a new empty geometry to a mesh
  39054. * @param mesh defines the mesh to attach the geometry to
  39055. * @returns the new {BABYLON.Geometry}
  39056. */
  39057. Geometry.CreateGeometryForMesh = function (mesh) {
  39058. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39059. geometry.applyToMesh(mesh);
  39060. return geometry;
  39061. };
  39062. Object.defineProperty(Geometry.prototype, "extend", {
  39063. /**
  39064. * Gets the current extend of the geometry
  39065. */
  39066. get: function () {
  39067. return this._extend;
  39068. },
  39069. enumerable: true,
  39070. configurable: true
  39071. });
  39072. /**
  39073. * Gets the hosting scene
  39074. * @returns the hosting {BABYLON.Scene}
  39075. */
  39076. Geometry.prototype.getScene = function () {
  39077. return this._scene;
  39078. };
  39079. /**
  39080. * Gets the hosting engine
  39081. * @returns the hosting {BABYLON.Engine}
  39082. */
  39083. Geometry.prototype.getEngine = function () {
  39084. return this._engine;
  39085. };
  39086. /**
  39087. * Defines if the geometry is ready to use
  39088. * @returns true if the geometry is ready to be used
  39089. */
  39090. Geometry.prototype.isReady = function () {
  39091. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39092. };
  39093. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39094. /**
  39095. * Gets a value indicating that the geometry should not be serialized
  39096. */
  39097. get: function () {
  39098. for (var index = 0; index < this._meshes.length; index++) {
  39099. if (!this._meshes[index].doNotSerialize) {
  39100. return false;
  39101. }
  39102. }
  39103. return true;
  39104. },
  39105. enumerable: true,
  39106. configurable: true
  39107. });
  39108. /** @hidden */
  39109. Geometry.prototype._rebuild = function () {
  39110. if (this._vertexArrayObjects) {
  39111. this._vertexArrayObjects = {};
  39112. }
  39113. // Index buffer
  39114. if (this._meshes.length !== 0 && this._indices) {
  39115. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39116. }
  39117. // Vertex buffers
  39118. for (var key in this._vertexBuffers) {
  39119. var vertexBuffer = this._vertexBuffers[key];
  39120. vertexBuffer._rebuild();
  39121. }
  39122. };
  39123. /**
  39124. * Affects all geometry data in one call
  39125. * @param vertexData defines the geometry data
  39126. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39127. */
  39128. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39129. vertexData.applyToGeometry(this, updatable);
  39130. this.notifyUpdate();
  39131. };
  39132. /**
  39133. * Set specific vertex data
  39134. * @param kind defines the data kind (Position, normal, etc...)
  39135. * @param data defines the vertex data to use
  39136. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39137. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39138. */
  39139. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39140. if (updatable === void 0) { updatable = false; }
  39141. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39142. this.setVerticesBuffer(buffer);
  39143. };
  39144. /**
  39145. * Removes a specific vertex data
  39146. * @param kind defines the data kind (Position, normal, etc...)
  39147. */
  39148. Geometry.prototype.removeVerticesData = function (kind) {
  39149. if (this._vertexBuffers[kind]) {
  39150. this._vertexBuffers[kind].dispose();
  39151. delete this._vertexBuffers[kind];
  39152. }
  39153. };
  39154. /**
  39155. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39156. * @param buffer defines the vertex buffer to use
  39157. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39158. */
  39159. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39160. if (totalVertices === void 0) { totalVertices = null; }
  39161. var kind = buffer.getKind();
  39162. if (this._vertexBuffers[kind]) {
  39163. this._vertexBuffers[kind].dispose();
  39164. }
  39165. this._vertexBuffers[kind] = buffer;
  39166. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39167. var data = buffer.getData();
  39168. if (totalVertices != null) {
  39169. this._totalVertices = totalVertices;
  39170. }
  39171. else {
  39172. if (data != null) {
  39173. this._totalVertices = data.length / (buffer.byteStride / 4);
  39174. }
  39175. }
  39176. this._updateExtend(data);
  39177. this._resetPointsArrayCache();
  39178. var meshes = this._meshes;
  39179. var numOfMeshes = meshes.length;
  39180. for (var index = 0; index < numOfMeshes; index++) {
  39181. var mesh = meshes[index];
  39182. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39183. mesh._createGlobalSubMesh(false);
  39184. mesh.computeWorldMatrix(true);
  39185. }
  39186. }
  39187. this.notifyUpdate(kind);
  39188. if (this._vertexArrayObjects) {
  39189. this._disposeVertexArrayObjects();
  39190. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39191. }
  39192. };
  39193. /**
  39194. * Update a specific vertex buffer
  39195. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39196. * It will do nothing if the buffer is not updatable
  39197. * @param kind defines the data kind (Position, normal, etc...)
  39198. * @param data defines the data to use
  39199. * @param offset defines the offset in the target buffer where to store the data
  39200. * @param useBytes set to true if the offset is in bytes
  39201. */
  39202. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39203. if (useBytes === void 0) { useBytes = false; }
  39204. var vertexBuffer = this.getVertexBuffer(kind);
  39205. if (!vertexBuffer) {
  39206. return;
  39207. }
  39208. vertexBuffer.updateDirectly(data, offset, useBytes);
  39209. this.notifyUpdate(kind);
  39210. };
  39211. /**
  39212. * Update a specific vertex buffer
  39213. * This function will create a new buffer if the current one is not updatable
  39214. * @param kind defines the data kind (Position, normal, etc...)
  39215. * @param data defines the data to use
  39216. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39217. */
  39218. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39219. if (updateExtends === void 0) { updateExtends = false; }
  39220. var vertexBuffer = this.getVertexBuffer(kind);
  39221. if (!vertexBuffer) {
  39222. return;
  39223. }
  39224. vertexBuffer.update(data);
  39225. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39226. this._updateBoundingInfo(updateExtends, data);
  39227. }
  39228. this.notifyUpdate(kind);
  39229. };
  39230. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39231. if (updateExtends) {
  39232. this._updateExtend(data);
  39233. }
  39234. var meshes = this._meshes;
  39235. var numOfMeshes = meshes.length;
  39236. this._resetPointsArrayCache();
  39237. for (var index = 0; index < numOfMeshes; index++) {
  39238. var mesh = meshes[index];
  39239. if (updateExtends) {
  39240. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39241. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39242. var subMesh = mesh.subMeshes[subIndex];
  39243. subMesh.refreshBoundingInfo();
  39244. }
  39245. }
  39246. }
  39247. };
  39248. /** @hidden */
  39249. Geometry.prototype._bind = function (effect, indexToBind) {
  39250. if (!effect) {
  39251. return;
  39252. }
  39253. if (indexToBind === undefined) {
  39254. indexToBind = this._indexBuffer;
  39255. }
  39256. var vbs = this.getVertexBuffers();
  39257. if (!vbs) {
  39258. return;
  39259. }
  39260. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39261. this._engine.bindBuffers(vbs, indexToBind, effect);
  39262. return;
  39263. }
  39264. // Using VAO
  39265. if (!this._vertexArrayObjects[effect.key]) {
  39266. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39267. }
  39268. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39269. };
  39270. /**
  39271. * Gets total number of vertices
  39272. * @returns the total number of vertices
  39273. */
  39274. Geometry.prototype.getTotalVertices = function () {
  39275. if (!this.isReady()) {
  39276. return 0;
  39277. }
  39278. return this._totalVertices;
  39279. };
  39280. /**
  39281. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39282. * @param kind defines the data kind (Position, normal, etc...)
  39283. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39284. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39285. * @returns a float array containing vertex data
  39286. */
  39287. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39288. var vertexBuffer = this.getVertexBuffer(kind);
  39289. if (!vertexBuffer) {
  39290. return null;
  39291. }
  39292. var data = vertexBuffer.getData();
  39293. if (!data) {
  39294. return null;
  39295. }
  39296. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39297. var count = this._totalVertices * vertexBuffer.getSize();
  39298. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39299. var copy_1 = new Array(count);
  39300. vertexBuffer.forEach(count, function (value, index) {
  39301. copy_1[index] = value;
  39302. });
  39303. return copy_1;
  39304. }
  39305. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39306. if (data instanceof Array) {
  39307. var offset = vertexBuffer.byteOffset / 4;
  39308. return BABYLON.Tools.Slice(data, offset, offset + count);
  39309. }
  39310. else if (data instanceof ArrayBuffer) {
  39311. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39312. }
  39313. else {
  39314. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39315. }
  39316. }
  39317. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39318. return BABYLON.Tools.Slice(data);
  39319. }
  39320. return data;
  39321. };
  39322. /**
  39323. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39324. * @param kind defines the data kind (Position, normal, etc...)
  39325. * @returns true if the vertex buffer with the specified kind is updatable
  39326. */
  39327. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39328. var vb = this._vertexBuffers[kind];
  39329. if (!vb) {
  39330. return false;
  39331. }
  39332. return vb.isUpdatable();
  39333. };
  39334. /**
  39335. * Gets a specific vertex buffer
  39336. * @param kind defines the data kind (Position, normal, etc...)
  39337. * @returns a {BABYLON.VertexBuffer}
  39338. */
  39339. Geometry.prototype.getVertexBuffer = function (kind) {
  39340. if (!this.isReady()) {
  39341. return null;
  39342. }
  39343. return this._vertexBuffers[kind];
  39344. };
  39345. /**
  39346. * Returns all vertex buffers
  39347. * @return an object holding all vertex buffers indexed by kind
  39348. */
  39349. Geometry.prototype.getVertexBuffers = function () {
  39350. if (!this.isReady()) {
  39351. return null;
  39352. }
  39353. return this._vertexBuffers;
  39354. };
  39355. /**
  39356. * Gets a boolean indicating if specific vertex buffer is present
  39357. * @param kind defines the data kind (Position, normal, etc...)
  39358. * @returns true if data is present
  39359. */
  39360. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39361. if (!this._vertexBuffers) {
  39362. if (this._delayInfo) {
  39363. return this._delayInfo.indexOf(kind) !== -1;
  39364. }
  39365. return false;
  39366. }
  39367. return this._vertexBuffers[kind] !== undefined;
  39368. };
  39369. /**
  39370. * Gets a list of all attached data kinds (Position, normal, etc...)
  39371. * @returns a list of string containing all kinds
  39372. */
  39373. Geometry.prototype.getVerticesDataKinds = function () {
  39374. var result = [];
  39375. var kind;
  39376. if (!this._vertexBuffers && this._delayInfo) {
  39377. for (kind in this._delayInfo) {
  39378. result.push(kind);
  39379. }
  39380. }
  39381. else {
  39382. for (kind in this._vertexBuffers) {
  39383. result.push(kind);
  39384. }
  39385. }
  39386. return result;
  39387. };
  39388. /**
  39389. * Update index buffer
  39390. * @param indices defines the indices to store in the index buffer
  39391. * @param offset defines the offset in the target buffer where to store the data
  39392. */
  39393. Geometry.prototype.updateIndices = function (indices, offset) {
  39394. if (!this._indexBuffer) {
  39395. return;
  39396. }
  39397. if (!this._indexBufferIsUpdatable) {
  39398. this.setIndices(indices, null, true);
  39399. }
  39400. else {
  39401. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39402. }
  39403. };
  39404. /**
  39405. * Creates a new index buffer
  39406. * @param indices defines the indices to store in the index buffer
  39407. * @param totalVertices defines the total number of vertices (could be null)
  39408. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39409. */
  39410. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39411. if (totalVertices === void 0) { totalVertices = null; }
  39412. if (updatable === void 0) { updatable = false; }
  39413. if (this._indexBuffer) {
  39414. this._engine._releaseBuffer(this._indexBuffer);
  39415. }
  39416. this._disposeVertexArrayObjects();
  39417. this._indices = indices;
  39418. this._indexBufferIsUpdatable = updatable;
  39419. if (this._meshes.length !== 0 && this._indices) {
  39420. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39421. }
  39422. if (totalVertices != undefined) { // including null and undefined
  39423. this._totalVertices = totalVertices;
  39424. }
  39425. var meshes = this._meshes;
  39426. var numOfMeshes = meshes.length;
  39427. for (var index = 0; index < numOfMeshes; index++) {
  39428. meshes[index]._createGlobalSubMesh(true);
  39429. }
  39430. this.notifyUpdate();
  39431. };
  39432. /**
  39433. * Return the total number of indices
  39434. * @returns the total number of indices
  39435. */
  39436. Geometry.prototype.getTotalIndices = function () {
  39437. if (!this.isReady()) {
  39438. return 0;
  39439. }
  39440. return this._indices.length;
  39441. };
  39442. /**
  39443. * Gets the index buffer array
  39444. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39445. * @returns the index buffer array
  39446. */
  39447. Geometry.prototype.getIndices = function (copyWhenShared) {
  39448. if (!this.isReady()) {
  39449. return null;
  39450. }
  39451. var orig = this._indices;
  39452. if (!copyWhenShared || this._meshes.length === 1) {
  39453. return orig;
  39454. }
  39455. else {
  39456. var len = orig.length;
  39457. var copy = [];
  39458. for (var i = 0; i < len; i++) {
  39459. copy.push(orig[i]);
  39460. }
  39461. return copy;
  39462. }
  39463. };
  39464. /**
  39465. * Gets the index buffer
  39466. * @return the index buffer
  39467. */
  39468. Geometry.prototype.getIndexBuffer = function () {
  39469. if (!this.isReady()) {
  39470. return null;
  39471. }
  39472. return this._indexBuffer;
  39473. };
  39474. /** @hidden */
  39475. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39476. if (effect === void 0) { effect = null; }
  39477. if (!effect || !this._vertexArrayObjects) {
  39478. return;
  39479. }
  39480. if (this._vertexArrayObjects[effect.key]) {
  39481. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39482. delete this._vertexArrayObjects[effect.key];
  39483. }
  39484. };
  39485. /**
  39486. * Release the associated resources for a specific mesh
  39487. * @param mesh defines the source mesh
  39488. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39489. */
  39490. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39491. var meshes = this._meshes;
  39492. var index = meshes.indexOf(mesh);
  39493. if (index === -1) {
  39494. return;
  39495. }
  39496. meshes.splice(index, 1);
  39497. mesh._geometry = null;
  39498. if (meshes.length === 0 && shouldDispose) {
  39499. this.dispose();
  39500. }
  39501. };
  39502. /**
  39503. * Apply current geometry to a given mesh
  39504. * @param mesh defines the mesh to apply geometry to
  39505. */
  39506. Geometry.prototype.applyToMesh = function (mesh) {
  39507. if (mesh._geometry === this) {
  39508. return;
  39509. }
  39510. var previousGeometry = mesh._geometry;
  39511. if (previousGeometry) {
  39512. previousGeometry.releaseForMesh(mesh);
  39513. }
  39514. var meshes = this._meshes;
  39515. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39516. mesh._geometry = this;
  39517. this._scene.pushGeometry(this);
  39518. meshes.push(mesh);
  39519. if (this.isReady()) {
  39520. this._applyToMesh(mesh);
  39521. }
  39522. else {
  39523. mesh._boundingInfo = this._boundingInfo;
  39524. }
  39525. };
  39526. Geometry.prototype._updateExtend = function (data) {
  39527. if (data === void 0) { data = null; }
  39528. if (!data) {
  39529. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39530. }
  39531. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39532. };
  39533. Geometry.prototype._applyToMesh = function (mesh) {
  39534. var numOfMeshes = this._meshes.length;
  39535. // vertexBuffers
  39536. for (var kind in this._vertexBuffers) {
  39537. if (numOfMeshes === 1) {
  39538. this._vertexBuffers[kind].create();
  39539. }
  39540. var buffer = this._vertexBuffers[kind].getBuffer();
  39541. if (buffer)
  39542. buffer.references = numOfMeshes;
  39543. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39544. if (!this._extend) {
  39545. this._updateExtend();
  39546. }
  39547. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39548. mesh._createGlobalSubMesh(false);
  39549. //bounding info was just created again, world matrix should be applied again.
  39550. mesh._updateBoundingInfo();
  39551. }
  39552. }
  39553. // indexBuffer
  39554. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39555. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39556. }
  39557. if (this._indexBuffer) {
  39558. this._indexBuffer.references = numOfMeshes;
  39559. }
  39560. };
  39561. Geometry.prototype.notifyUpdate = function (kind) {
  39562. if (this.onGeometryUpdated) {
  39563. this.onGeometryUpdated(this, kind);
  39564. }
  39565. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39566. var mesh = _a[_i];
  39567. mesh._markSubMeshesAsAttributesDirty();
  39568. }
  39569. };
  39570. /**
  39571. * Load the geometry if it was flagged as delay loaded
  39572. * @param scene defines the hosting scene
  39573. * @param onLoaded defines a callback called when the geometry is loaded
  39574. */
  39575. Geometry.prototype.load = function (scene, onLoaded) {
  39576. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39577. return;
  39578. }
  39579. if (this.isReady()) {
  39580. if (onLoaded) {
  39581. onLoaded();
  39582. }
  39583. return;
  39584. }
  39585. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39586. this._queueLoad(scene, onLoaded);
  39587. };
  39588. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39589. var _this = this;
  39590. if (!this.delayLoadingFile) {
  39591. return;
  39592. }
  39593. scene._addPendingData(this);
  39594. scene._loadFile(this.delayLoadingFile, function (data) {
  39595. if (!_this._delayLoadingFunction) {
  39596. return;
  39597. }
  39598. _this._delayLoadingFunction(JSON.parse(data), _this);
  39599. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39600. _this._delayInfo = [];
  39601. scene._removePendingData(_this);
  39602. var meshes = _this._meshes;
  39603. var numOfMeshes = meshes.length;
  39604. for (var index = 0; index < numOfMeshes; index++) {
  39605. _this._applyToMesh(meshes[index]);
  39606. }
  39607. if (onLoaded) {
  39608. onLoaded();
  39609. }
  39610. }, undefined, true);
  39611. };
  39612. /**
  39613. * Invert the geometry to move from a right handed system to a left handed one.
  39614. */
  39615. Geometry.prototype.toLeftHanded = function () {
  39616. // Flip faces
  39617. var tIndices = this.getIndices(false);
  39618. if (tIndices != null && tIndices.length > 0) {
  39619. for (var i = 0; i < tIndices.length; i += 3) {
  39620. var tTemp = tIndices[i + 0];
  39621. tIndices[i + 0] = tIndices[i + 2];
  39622. tIndices[i + 2] = tTemp;
  39623. }
  39624. this.setIndices(tIndices);
  39625. }
  39626. // Negate position.z
  39627. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39628. if (tPositions != null && tPositions.length > 0) {
  39629. for (var i = 0; i < tPositions.length; i += 3) {
  39630. tPositions[i + 2] = -tPositions[i + 2];
  39631. }
  39632. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39633. }
  39634. // Negate normal.z
  39635. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39636. if (tNormals != null && tNormals.length > 0) {
  39637. for (var i = 0; i < tNormals.length; i += 3) {
  39638. tNormals[i + 2] = -tNormals[i + 2];
  39639. }
  39640. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39641. }
  39642. };
  39643. // Cache
  39644. /** @hidden */
  39645. Geometry.prototype._resetPointsArrayCache = function () {
  39646. this._positions = null;
  39647. };
  39648. /** @hidden */
  39649. Geometry.prototype._generatePointsArray = function () {
  39650. if (this._positions)
  39651. return true;
  39652. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39653. if (!data || data.length === 0) {
  39654. return false;
  39655. }
  39656. this._positions = [];
  39657. for (var index = 0; index < data.length; index += 3) {
  39658. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39659. }
  39660. return true;
  39661. };
  39662. /**
  39663. * Gets a value indicating if the geometry is disposed
  39664. * @returns true if the geometry was disposed
  39665. */
  39666. Geometry.prototype.isDisposed = function () {
  39667. return this._isDisposed;
  39668. };
  39669. Geometry.prototype._disposeVertexArrayObjects = function () {
  39670. if (this._vertexArrayObjects) {
  39671. for (var kind in this._vertexArrayObjects) {
  39672. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39673. }
  39674. this._vertexArrayObjects = {};
  39675. }
  39676. };
  39677. /**
  39678. * Free all associated resources
  39679. */
  39680. Geometry.prototype.dispose = function () {
  39681. var meshes = this._meshes;
  39682. var numOfMeshes = meshes.length;
  39683. var index;
  39684. for (index = 0; index < numOfMeshes; index++) {
  39685. this.releaseForMesh(meshes[index]);
  39686. }
  39687. this._meshes = [];
  39688. this._disposeVertexArrayObjects();
  39689. for (var kind in this._vertexBuffers) {
  39690. this._vertexBuffers[kind].dispose();
  39691. }
  39692. this._vertexBuffers = {};
  39693. this._totalVertices = 0;
  39694. if (this._indexBuffer) {
  39695. this._engine._releaseBuffer(this._indexBuffer);
  39696. }
  39697. this._indexBuffer = null;
  39698. this._indices = [];
  39699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39700. this.delayLoadingFile = null;
  39701. this._delayLoadingFunction = null;
  39702. this._delayInfo = [];
  39703. this._boundingInfo = null;
  39704. this._scene.removeGeometry(this);
  39705. this._isDisposed = true;
  39706. };
  39707. /**
  39708. * Clone the current geometry into a new geometry
  39709. * @param id defines the unique ID of the new geometry
  39710. * @returns a new geometry object
  39711. */
  39712. Geometry.prototype.copy = function (id) {
  39713. var vertexData = new BABYLON.VertexData();
  39714. vertexData.indices = [];
  39715. var indices = this.getIndices();
  39716. if (indices) {
  39717. for (var index = 0; index < indices.length; index++) {
  39718. vertexData.indices.push(indices[index]);
  39719. }
  39720. }
  39721. var updatable = false;
  39722. var stopChecking = false;
  39723. var kind;
  39724. for (kind in this._vertexBuffers) {
  39725. // using slice() to make a copy of the array and not just reference it
  39726. var data = this.getVerticesData(kind);
  39727. if (data instanceof Float32Array) {
  39728. vertexData.set(new Float32Array(data), kind);
  39729. }
  39730. else {
  39731. vertexData.set(data.slice(0), kind);
  39732. }
  39733. if (!stopChecking) {
  39734. var vb = this.getVertexBuffer(kind);
  39735. if (vb) {
  39736. updatable = vb.isUpdatable();
  39737. stopChecking = !updatable;
  39738. }
  39739. }
  39740. }
  39741. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39742. geometry.delayLoadState = this.delayLoadState;
  39743. geometry.delayLoadingFile = this.delayLoadingFile;
  39744. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39745. for (kind in this._delayInfo) {
  39746. geometry._delayInfo = geometry._delayInfo || [];
  39747. geometry._delayInfo.push(kind);
  39748. }
  39749. // Bounding info
  39750. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39751. return geometry;
  39752. };
  39753. /**
  39754. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39755. * @return a JSON representation of the current geometry data (without the vertices data)
  39756. */
  39757. Geometry.prototype.serialize = function () {
  39758. var serializationObject = {};
  39759. serializationObject.id = this.id;
  39760. serializationObject.updatable = this._updatable;
  39761. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39762. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39763. }
  39764. return serializationObject;
  39765. };
  39766. Geometry.prototype.toNumberArray = function (origin) {
  39767. if (Array.isArray(origin)) {
  39768. return origin;
  39769. }
  39770. else {
  39771. return Array.prototype.slice.call(origin);
  39772. }
  39773. };
  39774. /**
  39775. * Serialize all vertices data into a JSON oject
  39776. * @returns a JSON representation of the current geometry data
  39777. */
  39778. Geometry.prototype.serializeVerticeData = function () {
  39779. var serializationObject = this.serialize();
  39780. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39781. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39782. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39783. serializationObject.positions._updatable = true;
  39784. }
  39785. }
  39786. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39787. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39788. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39789. serializationObject.normals._updatable = true;
  39790. }
  39791. }
  39792. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39793. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39794. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39795. serializationObject.tangets._updatable = true;
  39796. }
  39797. }
  39798. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39799. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39800. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39801. serializationObject.uvs._updatable = true;
  39802. }
  39803. }
  39804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39805. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39806. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39807. serializationObject.uv2s._updatable = true;
  39808. }
  39809. }
  39810. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39811. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39812. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39813. serializationObject.uv3s._updatable = true;
  39814. }
  39815. }
  39816. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39817. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39818. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39819. serializationObject.uv4s._updatable = true;
  39820. }
  39821. }
  39822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39823. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39824. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39825. serializationObject.uv5s._updatable = true;
  39826. }
  39827. }
  39828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39829. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39830. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39831. serializationObject.uv6s._updatable = true;
  39832. }
  39833. }
  39834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39835. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39836. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39837. serializationObject.colors._updatable = true;
  39838. }
  39839. }
  39840. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39841. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39842. serializationObject.matricesIndices._isExpanded = true;
  39843. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39844. serializationObject.matricesIndices._updatable = true;
  39845. }
  39846. }
  39847. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39848. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39849. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39850. serializationObject.matricesWeights._updatable = true;
  39851. }
  39852. }
  39853. serializationObject.indices = this.toNumberArray(this.getIndices());
  39854. return serializationObject;
  39855. };
  39856. // Statics
  39857. /**
  39858. * Extracts a clone of a mesh geometry
  39859. * @param mesh defines the source mesh
  39860. * @param id defines the unique ID of the new geometry object
  39861. * @returns the new geometry object
  39862. */
  39863. Geometry.ExtractFromMesh = function (mesh, id) {
  39864. var geometry = mesh._geometry;
  39865. if (!geometry) {
  39866. return null;
  39867. }
  39868. return geometry.copy(id);
  39869. };
  39870. /**
  39871. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39872. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39873. * Be aware Math.random() could cause collisions, but:
  39874. * "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"
  39875. * @returns a string containing a new GUID
  39876. */
  39877. Geometry.RandomId = function () {
  39878. return BABYLON.Tools.RandomId();
  39879. };
  39880. /** @hidden */
  39881. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39882. var scene = mesh.getScene();
  39883. // Geometry
  39884. var geometryId = parsedGeometry.geometryId;
  39885. if (geometryId) {
  39886. var geometry = scene.getGeometryByID(geometryId);
  39887. if (geometry) {
  39888. geometry.applyToMesh(mesh);
  39889. }
  39890. }
  39891. else if (parsedGeometry instanceof ArrayBuffer) {
  39892. var binaryInfo = mesh._binaryInfo;
  39893. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39894. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39895. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39896. }
  39897. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39898. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39899. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39900. }
  39901. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39902. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39903. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39904. }
  39905. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39906. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39907. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39908. }
  39909. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39910. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39912. }
  39913. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39914. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39915. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39916. }
  39917. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39918. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39919. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39920. }
  39921. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39922. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39924. }
  39925. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39926. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39928. }
  39929. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39930. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39931. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39932. }
  39933. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39934. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39935. var floatIndices = [];
  39936. for (var i = 0; i < matricesIndicesData.length; i++) {
  39937. var index = matricesIndicesData[i];
  39938. floatIndices.push(index & 0x000000FF);
  39939. floatIndices.push((index & 0x0000FF00) >> 8);
  39940. floatIndices.push((index & 0x00FF0000) >> 16);
  39941. floatIndices.push(index >> 24);
  39942. }
  39943. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39944. }
  39945. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39946. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39947. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39948. }
  39949. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39950. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39951. mesh.setIndices(indicesData, null);
  39952. }
  39953. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39954. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39955. mesh.subMeshes = [];
  39956. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39957. var materialIndex = subMeshesData[(i * 5) + 0];
  39958. var verticesStart = subMeshesData[(i * 5) + 1];
  39959. var verticesCount = subMeshesData[(i * 5) + 2];
  39960. var indexStart = subMeshesData[(i * 5) + 3];
  39961. var indexCount = subMeshesData[(i * 5) + 4];
  39962. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39963. }
  39964. }
  39965. }
  39966. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39967. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39968. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39969. if (parsedGeometry.tangents) {
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39971. }
  39972. if (parsedGeometry.uvs) {
  39973. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39974. }
  39975. if (parsedGeometry.uvs2) {
  39976. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39977. }
  39978. if (parsedGeometry.uvs3) {
  39979. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39980. }
  39981. if (parsedGeometry.uvs4) {
  39982. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39983. }
  39984. if (parsedGeometry.uvs5) {
  39985. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39986. }
  39987. if (parsedGeometry.uvs6) {
  39988. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39989. }
  39990. if (parsedGeometry.colors) {
  39991. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39992. }
  39993. if (parsedGeometry.matricesIndices) {
  39994. if (!parsedGeometry.matricesIndices._isExpanded) {
  39995. var floatIndices = [];
  39996. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39997. var matricesIndex = parsedGeometry.matricesIndices[i];
  39998. floatIndices.push(matricesIndex & 0x000000FF);
  39999. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40000. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40001. floatIndices.push(matricesIndex >> 24);
  40002. }
  40003. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40004. }
  40005. else {
  40006. delete parsedGeometry.matricesIndices._isExpanded;
  40007. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40008. }
  40009. }
  40010. if (parsedGeometry.matricesIndicesExtra) {
  40011. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40012. var floatIndices = [];
  40013. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40014. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40015. floatIndices.push(matricesIndex & 0x000000FF);
  40016. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40017. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40018. floatIndices.push(matricesIndex >> 24);
  40019. }
  40020. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40021. }
  40022. else {
  40023. delete parsedGeometry.matricesIndices._isExpanded;
  40024. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40025. }
  40026. }
  40027. if (parsedGeometry.matricesWeights) {
  40028. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40029. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40030. }
  40031. if (parsedGeometry.matricesWeightsExtra) {
  40032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40033. }
  40034. mesh.setIndices(parsedGeometry.indices, null);
  40035. }
  40036. // SubMeshes
  40037. if (parsedGeometry.subMeshes) {
  40038. mesh.subMeshes = [];
  40039. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40040. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40041. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40042. }
  40043. }
  40044. // Flat shading
  40045. if (mesh._shouldGenerateFlatShading) {
  40046. mesh.convertToFlatShadedMesh();
  40047. delete mesh._shouldGenerateFlatShading;
  40048. }
  40049. // Update
  40050. mesh.computeWorldMatrix(true);
  40051. // Octree
  40052. var sceneOctree = scene.selectionOctree;
  40053. if (sceneOctree !== undefined && sceneOctree !== null) {
  40054. sceneOctree.addMesh(mesh);
  40055. }
  40056. };
  40057. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40058. var epsilon = 1e-3;
  40059. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40060. return;
  40061. }
  40062. var noInfluenceBoneIndex = 0.0;
  40063. if (parsedGeometry.skeletonId > -1) {
  40064. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40065. if (!skeleton) {
  40066. return;
  40067. }
  40068. noInfluenceBoneIndex = skeleton.bones.length;
  40069. }
  40070. else {
  40071. return;
  40072. }
  40073. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40074. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40075. var matricesWeights = parsedGeometry.matricesWeights;
  40076. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40077. var influencers = parsedGeometry.numBoneInfluencer;
  40078. var size = matricesWeights.length;
  40079. for (var i = 0; i < size; i += 4) {
  40080. var weight = 0.0;
  40081. var firstZeroWeight = -1;
  40082. for (var j = 0; j < 4; j++) {
  40083. var w = matricesWeights[i + j];
  40084. weight += w;
  40085. if (w < epsilon && firstZeroWeight < 0) {
  40086. firstZeroWeight = j;
  40087. }
  40088. }
  40089. if (matricesWeightsExtra) {
  40090. for (var j = 0; j < 4; j++) {
  40091. var w = matricesWeightsExtra[i + j];
  40092. weight += w;
  40093. if (w < epsilon && firstZeroWeight < 0) {
  40094. firstZeroWeight = j + 4;
  40095. }
  40096. }
  40097. }
  40098. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40099. firstZeroWeight = influencers - 1;
  40100. }
  40101. if (weight > epsilon) {
  40102. var mweight = 1.0 / weight;
  40103. for (var j = 0; j < 4; j++) {
  40104. matricesWeights[i + j] *= mweight;
  40105. }
  40106. if (matricesWeightsExtra) {
  40107. for (var j = 0; j < 4; j++) {
  40108. matricesWeightsExtra[i + j] *= mweight;
  40109. }
  40110. }
  40111. }
  40112. else {
  40113. if (firstZeroWeight >= 4) {
  40114. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40115. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40116. }
  40117. else {
  40118. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40119. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40120. }
  40121. }
  40122. }
  40123. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40124. if (parsedGeometry.matricesWeightsExtra) {
  40125. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40126. }
  40127. };
  40128. /**
  40129. * Create a new geometry from persisted data (Using .babylon file format)
  40130. * @param parsedVertexData defines the persisted data
  40131. * @param scene defines the hosting scene
  40132. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40133. * @returns the new geometry object
  40134. */
  40135. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40136. if (scene.getGeometryByID(parsedVertexData.id)) {
  40137. return null; // null since geometry could be something else than a box...
  40138. }
  40139. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40140. if (BABYLON.Tags) {
  40141. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40142. }
  40143. if (parsedVertexData.delayLoadingFile) {
  40144. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40145. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40146. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40147. geometry._delayInfo = [];
  40148. if (parsedVertexData.hasUVs) {
  40149. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40150. }
  40151. if (parsedVertexData.hasUVs2) {
  40152. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40153. }
  40154. if (parsedVertexData.hasUVs3) {
  40155. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40156. }
  40157. if (parsedVertexData.hasUVs4) {
  40158. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40159. }
  40160. if (parsedVertexData.hasUVs5) {
  40161. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40162. }
  40163. if (parsedVertexData.hasUVs6) {
  40164. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40165. }
  40166. if (parsedVertexData.hasColors) {
  40167. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40168. }
  40169. if (parsedVertexData.hasMatricesIndices) {
  40170. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40171. }
  40172. if (parsedVertexData.hasMatricesWeights) {
  40173. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40174. }
  40175. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40176. }
  40177. else {
  40178. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40179. }
  40180. scene.pushGeometry(geometry, true);
  40181. return geometry;
  40182. };
  40183. return Geometry;
  40184. }());
  40185. BABYLON.Geometry = Geometry;
  40186. // Primitives
  40187. /// Abstract class
  40188. /**
  40189. * Abstract class used to provide common services for all typed geometries
  40190. * @hidden
  40191. */
  40192. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40193. __extends(_PrimitiveGeometry, _super);
  40194. /**
  40195. * Creates a new typed geometry
  40196. * @param id defines the unique ID of the geometry
  40197. * @param scene defines the hosting scene
  40198. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40199. * @param mesh defines the hosting mesh (can be null)
  40200. */
  40201. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40202. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40203. if (mesh === void 0) { mesh = null; }
  40204. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40205. _this._canBeRegenerated = _canBeRegenerated;
  40206. _this._beingRegenerated = true;
  40207. _this.regenerate();
  40208. _this._beingRegenerated = false;
  40209. return _this;
  40210. }
  40211. /**
  40212. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40213. * @returns true if the geometry can be regenerated
  40214. */
  40215. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40216. return this._canBeRegenerated;
  40217. };
  40218. /**
  40219. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40220. */
  40221. _PrimitiveGeometry.prototype.regenerate = function () {
  40222. if (!this._canBeRegenerated) {
  40223. return;
  40224. }
  40225. this._beingRegenerated = true;
  40226. this.setAllVerticesData(this._regenerateVertexData(), false);
  40227. this._beingRegenerated = false;
  40228. };
  40229. /**
  40230. * Clone the geometry
  40231. * @param id defines the unique ID of the new geometry
  40232. * @returns the new geometry
  40233. */
  40234. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40235. return _super.prototype.copy.call(this, id);
  40236. };
  40237. // overrides
  40238. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40239. if (!this._beingRegenerated) {
  40240. return;
  40241. }
  40242. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40243. };
  40244. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40245. if (!this._beingRegenerated) {
  40246. return;
  40247. }
  40248. _super.prototype.setVerticesData.call(this, kind, data, false);
  40249. };
  40250. // to override
  40251. /** @hidden */
  40252. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40253. throw new Error("Abstract method");
  40254. };
  40255. _PrimitiveGeometry.prototype.copy = function (id) {
  40256. throw new Error("Must be overriden in sub-classes.");
  40257. };
  40258. _PrimitiveGeometry.prototype.serialize = function () {
  40259. var serializationObject = _super.prototype.serialize.call(this);
  40260. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40261. return serializationObject;
  40262. };
  40263. return _PrimitiveGeometry;
  40264. }(Geometry));
  40265. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40266. /**
  40267. * Creates a ribbon geometry
  40268. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40269. */
  40270. var RibbonGeometry = /** @class */ (function (_super) {
  40271. __extends(RibbonGeometry, _super);
  40272. /**
  40273. * Creates a ribbon geometry
  40274. * @param id defines the unique ID of the geometry
  40275. * @param scene defines the hosting scene
  40276. * @param pathArray defines the array of paths to use
  40277. * @param closeArray defines if the last path and the first path must be joined
  40278. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40279. * @param offset defines the offset between points
  40280. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40281. * @param mesh defines the hosting mesh (can be null)
  40282. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40283. */
  40284. function RibbonGeometry(id, scene,
  40285. /**
  40286. * Defines the array of paths to use
  40287. */
  40288. pathArray,
  40289. /**
  40290. * Defines if the last and first points of each path in your pathArray must be joined
  40291. */
  40292. closeArray,
  40293. /**
  40294. * Defines if the last and first points of each path in your pathArray must be joined
  40295. */
  40296. closePath,
  40297. /**
  40298. * Defines the offset between points
  40299. */
  40300. offset, canBeRegenerated, mesh,
  40301. /**
  40302. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40303. */
  40304. side) {
  40305. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40306. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40307. _this.pathArray = pathArray;
  40308. _this.closeArray = closeArray;
  40309. _this.closePath = closePath;
  40310. _this.offset = offset;
  40311. _this.side = side;
  40312. return _this;
  40313. }
  40314. /** @hidden */
  40315. RibbonGeometry.prototype._regenerateVertexData = function () {
  40316. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40317. };
  40318. RibbonGeometry.prototype.copy = function (id) {
  40319. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40320. };
  40321. return RibbonGeometry;
  40322. }(_PrimitiveGeometry));
  40323. BABYLON.RibbonGeometry = RibbonGeometry;
  40324. /**
  40325. * Creates a box geometry
  40326. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40327. */
  40328. var BoxGeometry = /** @class */ (function (_super) {
  40329. __extends(BoxGeometry, _super);
  40330. /**
  40331. * Creates a box geometry
  40332. * @param id defines the unique ID of the geometry
  40333. * @param scene defines the hosting scene
  40334. * @param size defines the zise of the box (width, height and depth are the same)
  40335. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40336. * @param mesh defines the hosting mesh (can be null)
  40337. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40338. */
  40339. function BoxGeometry(id, scene,
  40340. /**
  40341. * Defines the zise of the box (width, height and depth are the same)
  40342. */
  40343. size, canBeRegenerated, mesh,
  40344. /**
  40345. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40346. */
  40347. side) {
  40348. if (mesh === void 0) { mesh = null; }
  40349. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40350. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40351. _this.size = size;
  40352. _this.side = side;
  40353. return _this;
  40354. }
  40355. BoxGeometry.prototype._regenerateVertexData = function () {
  40356. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40357. };
  40358. BoxGeometry.prototype.copy = function (id) {
  40359. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40360. };
  40361. BoxGeometry.prototype.serialize = function () {
  40362. var serializationObject = _super.prototype.serialize.call(this);
  40363. serializationObject.size = this.size;
  40364. return serializationObject;
  40365. };
  40366. BoxGeometry.Parse = function (parsedBox, scene) {
  40367. if (scene.getGeometryByID(parsedBox.id)) {
  40368. return null; // null since geometry could be something else than a box...
  40369. }
  40370. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40371. if (BABYLON.Tags) {
  40372. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40373. }
  40374. scene.pushGeometry(box, true);
  40375. return box;
  40376. };
  40377. return BoxGeometry;
  40378. }(_PrimitiveGeometry));
  40379. BABYLON.BoxGeometry = BoxGeometry;
  40380. /**
  40381. * Creates a sphere geometry
  40382. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40383. */
  40384. var SphereGeometry = /** @class */ (function (_super) {
  40385. __extends(SphereGeometry, _super);
  40386. /**
  40387. * Create a new sphere geometry
  40388. * @param id defines the unique ID of the geometry
  40389. * @param scene defines the hosting scene
  40390. * @param segments defines the number of segments to use to create the sphere
  40391. * @param diameter defines the diameter of the sphere
  40392. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40393. * @param mesh defines the hosting mesh (can be null)
  40394. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40395. */
  40396. function SphereGeometry(id, scene,
  40397. /**
  40398. * Defines the number of segments to use to create the sphere
  40399. */
  40400. segments,
  40401. /**
  40402. * Defines the diameter of the sphere
  40403. */
  40404. diameter, canBeRegenerated, mesh,
  40405. /**
  40406. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40407. */
  40408. side) {
  40409. if (mesh === void 0) { mesh = null; }
  40410. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40411. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40412. _this.segments = segments;
  40413. _this.diameter = diameter;
  40414. _this.side = side;
  40415. return _this;
  40416. }
  40417. SphereGeometry.prototype._regenerateVertexData = function () {
  40418. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40419. };
  40420. SphereGeometry.prototype.copy = function (id) {
  40421. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40422. };
  40423. SphereGeometry.prototype.serialize = function () {
  40424. var serializationObject = _super.prototype.serialize.call(this);
  40425. serializationObject.segments = this.segments;
  40426. serializationObject.diameter = this.diameter;
  40427. return serializationObject;
  40428. };
  40429. SphereGeometry.Parse = function (parsedSphere, scene) {
  40430. if (scene.getGeometryByID(parsedSphere.id)) {
  40431. return null; // null since geometry could be something else than a sphere...
  40432. }
  40433. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40434. if (BABYLON.Tags) {
  40435. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40436. }
  40437. scene.pushGeometry(sphere, true);
  40438. return sphere;
  40439. };
  40440. return SphereGeometry;
  40441. }(_PrimitiveGeometry));
  40442. BABYLON.SphereGeometry = SphereGeometry;
  40443. /**
  40444. * Creates a disc geometry
  40445. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40446. */
  40447. var DiscGeometry = /** @class */ (function (_super) {
  40448. __extends(DiscGeometry, _super);
  40449. /**
  40450. * Creates a new disc geometry
  40451. * @param id defines the unique ID of the geometry
  40452. * @param scene defines the hosting scene
  40453. * @param radius defines the radius of the disc
  40454. * @param tessellation defines the tesselation factor to apply to the disc
  40455. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40456. * @param mesh defines the hosting mesh (can be null)
  40457. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40458. */
  40459. function DiscGeometry(id, scene,
  40460. /**
  40461. * Defines the radius of the disc
  40462. */
  40463. radius,
  40464. /**
  40465. * Defines the tesselation factor to apply to the disc
  40466. */
  40467. tessellation, canBeRegenerated, mesh,
  40468. /**
  40469. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40470. */
  40471. side) {
  40472. if (mesh === void 0) { mesh = null; }
  40473. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40474. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40475. _this.radius = radius;
  40476. _this.tessellation = tessellation;
  40477. _this.side = side;
  40478. return _this;
  40479. }
  40480. DiscGeometry.prototype._regenerateVertexData = function () {
  40481. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40482. };
  40483. DiscGeometry.prototype.copy = function (id) {
  40484. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40485. };
  40486. return DiscGeometry;
  40487. }(_PrimitiveGeometry));
  40488. BABYLON.DiscGeometry = DiscGeometry;
  40489. /**
  40490. * Creates a new cylinder geometry
  40491. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40492. */
  40493. var CylinderGeometry = /** @class */ (function (_super) {
  40494. __extends(CylinderGeometry, _super);
  40495. /**
  40496. * Creates a new cylinder geometry
  40497. * @param id defines the unique ID of the geometry
  40498. * @param scene defines the hosting scene
  40499. * @param height defines the height of the cylinder
  40500. * @param diameterTop defines the diameter of the cylinder's top cap
  40501. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40502. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40503. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40504. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40505. * @param mesh defines the hosting mesh (can be null)
  40506. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40507. */
  40508. function CylinderGeometry(id, scene,
  40509. /**
  40510. * Defines the height of the cylinder
  40511. */
  40512. height,
  40513. /**
  40514. * Defines the diameter of the cylinder's top cap
  40515. */
  40516. diameterTop,
  40517. /**
  40518. * Defines the diameter of the cylinder's bottom cap
  40519. */
  40520. diameterBottom,
  40521. /**
  40522. * Defines the tessellation factor to apply to the cylinder
  40523. */
  40524. tessellation,
  40525. /**
  40526. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40527. */
  40528. subdivisions, canBeRegenerated, mesh,
  40529. /**
  40530. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40531. */
  40532. side) {
  40533. if (subdivisions === void 0) { subdivisions = 1; }
  40534. if (mesh === void 0) { mesh = null; }
  40535. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40536. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40537. _this.height = height;
  40538. _this.diameterTop = diameterTop;
  40539. _this.diameterBottom = diameterBottom;
  40540. _this.tessellation = tessellation;
  40541. _this.subdivisions = subdivisions;
  40542. _this.side = side;
  40543. return _this;
  40544. }
  40545. CylinderGeometry.prototype._regenerateVertexData = function () {
  40546. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40547. };
  40548. CylinderGeometry.prototype.copy = function (id) {
  40549. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40550. };
  40551. CylinderGeometry.prototype.serialize = function () {
  40552. var serializationObject = _super.prototype.serialize.call(this);
  40553. serializationObject.height = this.height;
  40554. serializationObject.diameterTop = this.diameterTop;
  40555. serializationObject.diameterBottom = this.diameterBottom;
  40556. serializationObject.tessellation = this.tessellation;
  40557. return serializationObject;
  40558. };
  40559. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40560. if (scene.getGeometryByID(parsedCylinder.id)) {
  40561. return null; // null since geometry could be something else than a cylinder...
  40562. }
  40563. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40564. if (BABYLON.Tags) {
  40565. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40566. }
  40567. scene.pushGeometry(cylinder, true);
  40568. return cylinder;
  40569. };
  40570. return CylinderGeometry;
  40571. }(_PrimitiveGeometry));
  40572. BABYLON.CylinderGeometry = CylinderGeometry;
  40573. /**
  40574. * Creates a new torus geometry
  40575. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40576. */
  40577. var TorusGeometry = /** @class */ (function (_super) {
  40578. __extends(TorusGeometry, _super);
  40579. /**
  40580. * Creates a new torus geometry
  40581. * @param id defines the unique ID of the geometry
  40582. * @param scene defines the hosting scene
  40583. * @param diameter defines the diameter of the torus
  40584. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40585. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40586. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40587. * @param mesh defines the hosting mesh (can be null)
  40588. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40589. */
  40590. function TorusGeometry(id, scene,
  40591. /**
  40592. * Defines the diameter of the torus
  40593. */
  40594. diameter,
  40595. /**
  40596. * Defines the thickness of the torus (ie. internal diameter)
  40597. */
  40598. thickness,
  40599. /**
  40600. * Defines the tesselation factor to apply to the torus
  40601. */
  40602. tessellation, canBeRegenerated, mesh,
  40603. /**
  40604. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40605. */
  40606. side) {
  40607. if (mesh === void 0) { mesh = null; }
  40608. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40609. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40610. _this.diameter = diameter;
  40611. _this.thickness = thickness;
  40612. _this.tessellation = tessellation;
  40613. _this.side = side;
  40614. return _this;
  40615. }
  40616. TorusGeometry.prototype._regenerateVertexData = function () {
  40617. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40618. };
  40619. TorusGeometry.prototype.copy = function (id) {
  40620. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40621. };
  40622. TorusGeometry.prototype.serialize = function () {
  40623. var serializationObject = _super.prototype.serialize.call(this);
  40624. serializationObject.diameter = this.diameter;
  40625. serializationObject.thickness = this.thickness;
  40626. serializationObject.tessellation = this.tessellation;
  40627. return serializationObject;
  40628. };
  40629. TorusGeometry.Parse = function (parsedTorus, scene) {
  40630. if (scene.getGeometryByID(parsedTorus.id)) {
  40631. return null; // null since geometry could be something else than a torus...
  40632. }
  40633. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40634. if (BABYLON.Tags) {
  40635. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40636. }
  40637. scene.pushGeometry(torus, true);
  40638. return torus;
  40639. };
  40640. return TorusGeometry;
  40641. }(_PrimitiveGeometry));
  40642. BABYLON.TorusGeometry = TorusGeometry;
  40643. /**
  40644. * Creates a new ground geometry
  40645. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40646. */
  40647. var GroundGeometry = /** @class */ (function (_super) {
  40648. __extends(GroundGeometry, _super);
  40649. /**
  40650. * Creates a new ground geometry
  40651. * @param id defines the unique ID of the geometry
  40652. * @param scene defines the hosting scene
  40653. * @param width defines the width of the ground
  40654. * @param height defines the height of the ground
  40655. * @param subdivisions defines the subdivisions to apply to the ground
  40656. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40657. * @param mesh defines the hosting mesh (can be null)
  40658. */
  40659. function GroundGeometry(id, scene,
  40660. /**
  40661. * Defines the width of the ground
  40662. */
  40663. width,
  40664. /**
  40665. * Defines the height of the ground
  40666. */
  40667. height,
  40668. /**
  40669. * Defines the subdivisions to apply to the ground
  40670. */
  40671. subdivisions, canBeRegenerated, mesh) {
  40672. if (mesh === void 0) { mesh = null; }
  40673. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40674. _this.width = width;
  40675. _this.height = height;
  40676. _this.subdivisions = subdivisions;
  40677. return _this;
  40678. }
  40679. GroundGeometry.prototype._regenerateVertexData = function () {
  40680. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40681. };
  40682. GroundGeometry.prototype.copy = function (id) {
  40683. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40684. };
  40685. GroundGeometry.prototype.serialize = function () {
  40686. var serializationObject = _super.prototype.serialize.call(this);
  40687. serializationObject.width = this.width;
  40688. serializationObject.height = this.height;
  40689. serializationObject.subdivisions = this.subdivisions;
  40690. return serializationObject;
  40691. };
  40692. GroundGeometry.Parse = function (parsedGround, scene) {
  40693. if (scene.getGeometryByID(parsedGround.id)) {
  40694. return null; // null since geometry could be something else than a ground...
  40695. }
  40696. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40697. if (BABYLON.Tags) {
  40698. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40699. }
  40700. scene.pushGeometry(ground, true);
  40701. return ground;
  40702. };
  40703. return GroundGeometry;
  40704. }(_PrimitiveGeometry));
  40705. BABYLON.GroundGeometry = GroundGeometry;
  40706. /**
  40707. * Creates a tiled ground geometry
  40708. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40709. */
  40710. var TiledGroundGeometry = /** @class */ (function (_super) {
  40711. __extends(TiledGroundGeometry, _super);
  40712. /**
  40713. * Creates a tiled ground geometry
  40714. * @param id defines the unique ID of the geometry
  40715. * @param scene defines the hosting scene
  40716. * @param xmin defines the minimum value on X axis
  40717. * @param zmin defines the minimum value on Z axis
  40718. * @param xmax defines the maximum value on X axis
  40719. * @param zmax defines the maximum value on Z axis
  40720. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40721. * @param precision defines the precision to use when computing the tiles
  40722. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40723. * @param mesh defines the hosting mesh (can be null)
  40724. */
  40725. function TiledGroundGeometry(id, scene,
  40726. /**
  40727. * Defines the minimum value on X axis
  40728. */
  40729. xmin,
  40730. /**
  40731. * Defines the minimum value on Z axis
  40732. */
  40733. zmin,
  40734. /**
  40735. * Defines the maximum value on X axis
  40736. */
  40737. xmax,
  40738. /**
  40739. * Defines the maximum value on Z axis
  40740. */
  40741. zmax,
  40742. /**
  40743. * Defines the subdivisions to apply to the ground
  40744. */
  40745. subdivisions,
  40746. /**
  40747. * Defines the precision to use when computing the tiles
  40748. */
  40749. precision, canBeRegenerated, mesh) {
  40750. if (mesh === void 0) { mesh = null; }
  40751. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40752. _this.xmin = xmin;
  40753. _this.zmin = zmin;
  40754. _this.xmax = xmax;
  40755. _this.zmax = zmax;
  40756. _this.subdivisions = subdivisions;
  40757. _this.precision = precision;
  40758. return _this;
  40759. }
  40760. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40761. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40762. };
  40763. TiledGroundGeometry.prototype.copy = function (id) {
  40764. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40765. };
  40766. return TiledGroundGeometry;
  40767. }(_PrimitiveGeometry));
  40768. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40769. /**
  40770. * Creates a plane geometry
  40771. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40772. */
  40773. var PlaneGeometry = /** @class */ (function (_super) {
  40774. __extends(PlaneGeometry, _super);
  40775. /**
  40776. * Creates a plane geometry
  40777. * @param id defines the unique ID of the geometry
  40778. * @param scene defines the hosting scene
  40779. * @param size defines the size of the plane (width === height)
  40780. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40781. * @param mesh defines the hosting mesh (can be null)
  40782. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40783. */
  40784. function PlaneGeometry(id, scene,
  40785. /**
  40786. * Defines the size of the plane (width === height)
  40787. */
  40788. size, canBeRegenerated, mesh,
  40789. /**
  40790. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40791. */
  40792. side) {
  40793. if (mesh === void 0) { mesh = null; }
  40794. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40795. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40796. _this.size = size;
  40797. _this.side = side;
  40798. return _this;
  40799. }
  40800. PlaneGeometry.prototype._regenerateVertexData = function () {
  40801. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40802. };
  40803. PlaneGeometry.prototype.copy = function (id) {
  40804. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40805. };
  40806. PlaneGeometry.prototype.serialize = function () {
  40807. var serializationObject = _super.prototype.serialize.call(this);
  40808. serializationObject.size = this.size;
  40809. return serializationObject;
  40810. };
  40811. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40812. if (scene.getGeometryByID(parsedPlane.id)) {
  40813. return null; // null since geometry could be something else than a ground...
  40814. }
  40815. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40816. if (BABYLON.Tags) {
  40817. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40818. }
  40819. scene.pushGeometry(plane, true);
  40820. return plane;
  40821. };
  40822. return PlaneGeometry;
  40823. }(_PrimitiveGeometry));
  40824. BABYLON.PlaneGeometry = PlaneGeometry;
  40825. /**
  40826. * Creates a torus knot geometry
  40827. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40828. */
  40829. var TorusKnotGeometry = /** @class */ (function (_super) {
  40830. __extends(TorusKnotGeometry, _super);
  40831. /**
  40832. * Creates a torus knot geometry
  40833. * @param id defines the unique ID of the geometry
  40834. * @param scene defines the hosting scene
  40835. * @param radius defines the radius of the torus knot
  40836. * @param tube defines the thickness of the torus knot tube
  40837. * @param radialSegments defines the number of radial segments
  40838. * @param tubularSegments defines the number of tubular segments
  40839. * @param p defines the first number of windings
  40840. * @param q defines the second number of windings
  40841. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40842. * @param mesh defines the hosting mesh (can be null)
  40843. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40844. */
  40845. function TorusKnotGeometry(id, scene,
  40846. /**
  40847. * Defines the radius of the torus knot
  40848. */
  40849. radius,
  40850. /**
  40851. * Defines the thickness of the torus knot tube
  40852. */
  40853. tube,
  40854. /**
  40855. * Defines the number of radial segments
  40856. */
  40857. radialSegments,
  40858. /**
  40859. * Defines the number of tubular segments
  40860. */
  40861. tubularSegments,
  40862. /**
  40863. * Defines the first number of windings
  40864. */
  40865. p,
  40866. /**
  40867. * Defines the second number of windings
  40868. */
  40869. q, canBeRegenerated, mesh,
  40870. /**
  40871. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40872. */
  40873. side) {
  40874. if (mesh === void 0) { mesh = null; }
  40875. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40876. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40877. _this.radius = radius;
  40878. _this.tube = tube;
  40879. _this.radialSegments = radialSegments;
  40880. _this.tubularSegments = tubularSegments;
  40881. _this.p = p;
  40882. _this.q = q;
  40883. _this.side = side;
  40884. return _this;
  40885. }
  40886. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40887. 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 });
  40888. };
  40889. TorusKnotGeometry.prototype.copy = function (id) {
  40890. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40891. };
  40892. TorusKnotGeometry.prototype.serialize = function () {
  40893. var serializationObject = _super.prototype.serialize.call(this);
  40894. serializationObject.radius = this.radius;
  40895. serializationObject.tube = this.tube;
  40896. serializationObject.radialSegments = this.radialSegments;
  40897. serializationObject.tubularSegments = this.tubularSegments;
  40898. serializationObject.p = this.p;
  40899. serializationObject.q = this.q;
  40900. return serializationObject;
  40901. };
  40902. ;
  40903. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40904. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40905. return null; // null since geometry could be something else than a ground...
  40906. }
  40907. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40908. if (BABYLON.Tags) {
  40909. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40910. }
  40911. scene.pushGeometry(torusKnot, true);
  40912. return torusKnot;
  40913. };
  40914. return TorusKnotGeometry;
  40915. }(_PrimitiveGeometry));
  40916. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40917. //}
  40918. })(BABYLON || (BABYLON = {}));
  40919. //# sourceMappingURL=babylon.geometry.js.map
  40920. var BABYLON;
  40921. (function (BABYLON) {
  40922. /**
  40923. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40924. */
  40925. var PerformanceMonitor = /** @class */ (function () {
  40926. /**
  40927. * constructor
  40928. * @param frameSampleSize The number of samples required to saturate the sliding window
  40929. */
  40930. function PerformanceMonitor(frameSampleSize) {
  40931. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40932. this._enabled = true;
  40933. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40934. }
  40935. /**
  40936. * Samples current frame
  40937. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40938. */
  40939. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40940. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40941. if (!this._enabled)
  40942. return;
  40943. if (this._lastFrameTimeMs != null) {
  40944. var dt = timeMs - this._lastFrameTimeMs;
  40945. this._rollingFrameTime.add(dt);
  40946. }
  40947. this._lastFrameTimeMs = timeMs;
  40948. };
  40949. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40950. /**
  40951. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40952. * @return Average frame time in milliseconds
  40953. */
  40954. get: function () {
  40955. return this._rollingFrameTime.average;
  40956. },
  40957. enumerable: true,
  40958. configurable: true
  40959. });
  40960. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40961. /**
  40962. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40963. * @return Frame time variance in milliseconds squared
  40964. */
  40965. get: function () {
  40966. return this._rollingFrameTime.variance;
  40967. },
  40968. enumerable: true,
  40969. configurable: true
  40970. });
  40971. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40972. /**
  40973. * Returns the frame time of the most recent frame
  40974. * @return Frame time in milliseconds
  40975. */
  40976. get: function () {
  40977. return this._rollingFrameTime.history(0);
  40978. },
  40979. enumerable: true,
  40980. configurable: true
  40981. });
  40982. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40983. /**
  40984. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40985. * @return Framerate in frames per second
  40986. */
  40987. get: function () {
  40988. return 1000.0 / this._rollingFrameTime.average;
  40989. },
  40990. enumerable: true,
  40991. configurable: true
  40992. });
  40993. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40994. /**
  40995. * Returns the average framerate in frames per second using the most recent frame time
  40996. * @return Framerate in frames per second
  40997. */
  40998. get: function () {
  40999. var history = this._rollingFrameTime.history(0);
  41000. if (history === 0) {
  41001. return 0;
  41002. }
  41003. return 1000.0 / history;
  41004. },
  41005. enumerable: true,
  41006. configurable: true
  41007. });
  41008. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41009. /**
  41010. * Returns true if enough samples have been taken to completely fill the sliding window
  41011. * @return true if saturated
  41012. */
  41013. get: function () {
  41014. return this._rollingFrameTime.isSaturated();
  41015. },
  41016. enumerable: true,
  41017. configurable: true
  41018. });
  41019. /**
  41020. * Enables contributions to the sliding window sample set
  41021. */
  41022. PerformanceMonitor.prototype.enable = function () {
  41023. this._enabled = true;
  41024. };
  41025. /**
  41026. * Disables contributions to the sliding window sample set
  41027. * Samples will not be interpolated over the disabled period
  41028. */
  41029. PerformanceMonitor.prototype.disable = function () {
  41030. this._enabled = false;
  41031. //clear last sample to avoid interpolating over the disabled period when next enabled
  41032. this._lastFrameTimeMs = null;
  41033. };
  41034. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41035. /**
  41036. * Returns true if sampling is enabled
  41037. * @return true if enabled
  41038. */
  41039. get: function () {
  41040. return this._enabled;
  41041. },
  41042. enumerable: true,
  41043. configurable: true
  41044. });
  41045. /**
  41046. * Resets performance monitor
  41047. */
  41048. PerformanceMonitor.prototype.reset = function () {
  41049. //clear last sample to avoid interpolating over the disabled period when next enabled
  41050. this._lastFrameTimeMs = null;
  41051. //wipe record
  41052. this._rollingFrameTime.reset();
  41053. };
  41054. return PerformanceMonitor;
  41055. }());
  41056. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41057. /**
  41058. * RollingAverage
  41059. *
  41060. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41061. */
  41062. var RollingAverage = /** @class */ (function () {
  41063. /**
  41064. * constructor
  41065. * @param length The number of samples required to saturate the sliding window
  41066. */
  41067. function RollingAverage(length) {
  41068. this._samples = new Array(length);
  41069. this.reset();
  41070. }
  41071. /**
  41072. * Adds a sample to the sample set
  41073. * @param v The sample value
  41074. */
  41075. RollingAverage.prototype.add = function (v) {
  41076. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41077. var delta;
  41078. //we need to check if we've already wrapped round
  41079. if (this.isSaturated()) {
  41080. //remove bottom of stack from mean
  41081. var bottomValue = this._samples[this._pos];
  41082. delta = bottomValue - this.average;
  41083. this.average -= delta / (this._sampleCount - 1);
  41084. this._m2 -= delta * (bottomValue - this.average);
  41085. }
  41086. else {
  41087. this._sampleCount++;
  41088. }
  41089. //add new value to mean
  41090. delta = v - this.average;
  41091. this.average += delta / (this._sampleCount);
  41092. this._m2 += delta * (v - this.average);
  41093. //set the new variance
  41094. this.variance = this._m2 / (this._sampleCount - 1);
  41095. this._samples[this._pos] = v;
  41096. this._pos++;
  41097. this._pos %= this._samples.length; //positive wrap around
  41098. };
  41099. /**
  41100. * Returns previously added values or null if outside of history or outside the sliding window domain
  41101. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41102. * @return Value previously recorded with add() or null if outside of range
  41103. */
  41104. RollingAverage.prototype.history = function (i) {
  41105. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41106. return 0;
  41107. }
  41108. var i0 = this._wrapPosition(this._pos - 1.0);
  41109. return this._samples[this._wrapPosition(i0 - i)];
  41110. };
  41111. /**
  41112. * Returns true if enough samples have been taken to completely fill the sliding window
  41113. * @return true if sample-set saturated
  41114. */
  41115. RollingAverage.prototype.isSaturated = function () {
  41116. return this._sampleCount >= this._samples.length;
  41117. };
  41118. /**
  41119. * Resets the rolling average (equivalent to 0 samples taken so far)
  41120. */
  41121. RollingAverage.prototype.reset = function () {
  41122. this.average = 0;
  41123. this.variance = 0;
  41124. this._sampleCount = 0;
  41125. this._pos = 0;
  41126. this._m2 = 0;
  41127. };
  41128. /**
  41129. * Wraps a value around the sample range boundaries
  41130. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41131. * @return Wrapped position in sample range
  41132. */
  41133. RollingAverage.prototype._wrapPosition = function (i) {
  41134. var max = this._samples.length;
  41135. return ((i % max) + max) % max;
  41136. };
  41137. return RollingAverage;
  41138. }());
  41139. BABYLON.RollingAverage = RollingAverage;
  41140. })(BABYLON || (BABYLON = {}));
  41141. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41142. var BABYLON;
  41143. (function (BABYLON) {
  41144. /**
  41145. * "Static Class" containing the most commonly used helper while dealing with material for
  41146. * rendering purpose.
  41147. *
  41148. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41149. *
  41150. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41151. */
  41152. var MaterialHelper = /** @class */ (function () {
  41153. function MaterialHelper() {
  41154. }
  41155. /**
  41156. * Bind the current view position to an effect.
  41157. * @param effect The effect to be bound
  41158. * @param scene The scene the eyes position is used from
  41159. */
  41160. MaterialHelper.BindEyePosition = function (effect, scene) {
  41161. if (scene._forcedViewPosition) {
  41162. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41163. return;
  41164. }
  41165. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41166. };
  41167. /**
  41168. * Helps preparing the defines values about the UVs in used in the effect.
  41169. * UVs are shared as much as we can accross chanels in the shaders.
  41170. * @param texture The texture we are preparing the UVs for
  41171. * @param defines The defines to update
  41172. * @param key The chanel key "diffuse", "specular"... used in the shader
  41173. */
  41174. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41175. defines._needUVs = true;
  41176. defines[key] = true;
  41177. if (texture.getTextureMatrix().isIdentity(true)) {
  41178. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41179. if (texture.coordinatesIndex === 0) {
  41180. defines["MAINUV1"] = true;
  41181. }
  41182. else {
  41183. defines["MAINUV2"] = true;
  41184. }
  41185. }
  41186. else {
  41187. defines[key + "DIRECTUV"] = 0;
  41188. }
  41189. };
  41190. /**
  41191. * Binds a texture matrix value to its corrsponding uniform
  41192. * @param texture The texture to bind the matrix for
  41193. * @param uniformBuffer The uniform buffer receivin the data
  41194. * @param key The chanel key "diffuse", "specular"... used in the shader
  41195. */
  41196. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41197. var matrix = texture.getTextureMatrix();
  41198. if (!matrix.isIdentity(true)) {
  41199. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41200. }
  41201. };
  41202. /**
  41203. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41204. * @param mesh defines the current mesh
  41205. * @param scene defines the current scene
  41206. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41207. * @param pointsCloud defines if point cloud rendering has to be turned on
  41208. * @param fogEnabled defines if fog has to be turned on
  41209. * @param alphaTest defines if alpha testing has to be turned on
  41210. * @param defines defines the current list of defines
  41211. */
  41212. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41213. if (defines._areMiscDirty) {
  41214. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41215. defines["POINTSIZE"] = pointsCloud;
  41216. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41217. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41218. defines["ALPHATEST"] = alphaTest;
  41219. }
  41220. };
  41221. /**
  41222. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41223. * @param scene defines the current scene
  41224. * @param engine defines the current engine
  41225. * @param defines specifies the list of active defines
  41226. * @param useInstances defines if instances have to be turned on
  41227. * @param useClipPlane defines if clip plane have to be turned on
  41228. */
  41229. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41230. if (useClipPlane === void 0) { useClipPlane = null; }
  41231. var changed = false;
  41232. if (useClipPlane == null) {
  41233. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41234. }
  41235. if (defines["CLIPPLANE"] !== useClipPlane) {
  41236. defines["CLIPPLANE"] = useClipPlane;
  41237. changed = true;
  41238. }
  41239. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41240. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41241. changed = true;
  41242. }
  41243. if (defines["INSTANCES"] !== useInstances) {
  41244. defines["INSTANCES"] = useInstances;
  41245. changed = true;
  41246. }
  41247. if (changed) {
  41248. defines.markAsUnprocessed();
  41249. }
  41250. };
  41251. /**
  41252. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41253. * @param mesh The mesh containing the geometry data we will draw
  41254. * @param defines The defines to update
  41255. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41256. * @param useBones Precise whether bones should be used or not (override mesh info)
  41257. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41258. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41259. * @returns false if defines are considered not dirty and have not been checked
  41260. */
  41261. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41262. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41263. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41264. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41265. return false;
  41266. }
  41267. defines._normals = defines._needNormals;
  41268. defines._uvs = defines._needUVs;
  41269. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41270. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41271. defines["TANGENT"] = true;
  41272. }
  41273. if (defines._needUVs) {
  41274. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41275. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41276. }
  41277. else {
  41278. defines["UV1"] = false;
  41279. defines["UV2"] = false;
  41280. }
  41281. if (useVertexColor) {
  41282. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41283. defines["VERTEXCOLOR"] = hasVertexColors;
  41284. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41285. }
  41286. if (useBones) {
  41287. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41288. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41289. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41290. }
  41291. else {
  41292. defines["NUM_BONE_INFLUENCERS"] = 0;
  41293. defines["BonesPerMesh"] = 0;
  41294. }
  41295. }
  41296. if (useMorphTargets) {
  41297. var manager = mesh.morphTargetManager;
  41298. if (manager) {
  41299. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41300. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41301. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41302. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41303. }
  41304. else {
  41305. defines["MORPHTARGETS_TANGENT"] = false;
  41306. defines["MORPHTARGETS_NORMAL"] = false;
  41307. defines["MORPHTARGETS"] = false;
  41308. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41309. }
  41310. }
  41311. return true;
  41312. };
  41313. /**
  41314. * Prepares the defines related to the light information passed in parameter
  41315. * @param scene The scene we are intending to draw
  41316. * @param mesh The mesh the effect is compiling for
  41317. * @param defines The defines to update
  41318. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41319. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41320. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41321. * @returns true if normals will be required for the rest of the effect
  41322. */
  41323. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41324. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41325. if (disableLighting === void 0) { disableLighting = false; }
  41326. if (!defines._areLightsDirty) {
  41327. return defines._needNormals;
  41328. }
  41329. var lightIndex = 0;
  41330. var needNormals = false;
  41331. var needRebuild = false;
  41332. var lightmapMode = false;
  41333. var shadowEnabled = false;
  41334. var specularEnabled = false;
  41335. if (scene.lightsEnabled && !disableLighting) {
  41336. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41337. var light = _a[_i];
  41338. needNormals = true;
  41339. if (defines["LIGHT" + lightIndex] === undefined) {
  41340. needRebuild = true;
  41341. }
  41342. defines["LIGHT" + lightIndex] = true;
  41343. defines["SPOTLIGHT" + lightIndex] = false;
  41344. defines["HEMILIGHT" + lightIndex] = false;
  41345. defines["POINTLIGHT" + lightIndex] = false;
  41346. defines["DIRLIGHT" + lightIndex] = false;
  41347. var type;
  41348. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41349. type = "SPOTLIGHT" + lightIndex;
  41350. var spotLight = light;
  41351. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41352. }
  41353. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41354. type = "HEMILIGHT" + lightIndex;
  41355. }
  41356. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41357. type = "POINTLIGHT" + lightIndex;
  41358. }
  41359. else {
  41360. type = "DIRLIGHT" + lightIndex;
  41361. }
  41362. defines[type] = true;
  41363. // Specular
  41364. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41365. specularEnabled = true;
  41366. }
  41367. // Shadows
  41368. defines["SHADOW" + lightIndex] = false;
  41369. defines["SHADOWPCF" + lightIndex] = false;
  41370. defines["SHADOWPCSS" + lightIndex] = false;
  41371. defines["SHADOWPOISSON" + lightIndex] = false;
  41372. defines["SHADOWESM" + lightIndex] = false;
  41373. defines["SHADOWCUBE" + lightIndex] = false;
  41374. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41375. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41376. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41377. var shadowGenerator = light.getShadowGenerator();
  41378. if (shadowGenerator) {
  41379. shadowEnabled = true;
  41380. shadowGenerator.prepareDefines(defines, lightIndex);
  41381. }
  41382. }
  41383. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41384. lightmapMode = true;
  41385. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41386. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41387. }
  41388. else {
  41389. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41390. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41391. }
  41392. lightIndex++;
  41393. if (lightIndex === maxSimultaneousLights)
  41394. break;
  41395. }
  41396. }
  41397. defines["SPECULARTERM"] = specularEnabled;
  41398. defines["SHADOWS"] = shadowEnabled;
  41399. // Resetting all other lights if any
  41400. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41401. if (defines["LIGHT" + index] !== undefined) {
  41402. defines["LIGHT" + index] = false;
  41403. defines["HEMILIGHT" + lightIndex] = false;
  41404. defines["POINTLIGHT" + lightIndex] = false;
  41405. defines["DIRLIGHT" + lightIndex] = false;
  41406. defines["SPOTLIGHT" + lightIndex] = false;
  41407. defines["SHADOW" + lightIndex] = false;
  41408. }
  41409. }
  41410. var caps = scene.getEngine().getCaps();
  41411. if (defines["SHADOWFLOAT"] === undefined) {
  41412. needRebuild = true;
  41413. }
  41414. defines["SHADOWFLOAT"] = shadowEnabled &&
  41415. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41416. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41417. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41418. if (needRebuild) {
  41419. defines.rebuild();
  41420. }
  41421. return needNormals;
  41422. };
  41423. /**
  41424. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41425. * that won t be acctive due to defines being turned off.
  41426. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41427. * @param samplersList The samplers list
  41428. * @param defines The defines helping in the list generation
  41429. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41430. */
  41431. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41432. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41433. var uniformsList;
  41434. var uniformBuffersList = null;
  41435. if (uniformsListOrOptions.uniformsNames) {
  41436. var options = uniformsListOrOptions;
  41437. uniformsList = options.uniformsNames;
  41438. uniformBuffersList = options.uniformBuffersNames;
  41439. samplersList = options.samplers;
  41440. defines = options.defines;
  41441. maxSimultaneousLights = options.maxSimultaneousLights;
  41442. }
  41443. else {
  41444. uniformsList = uniformsListOrOptions;
  41445. if (!samplersList) {
  41446. samplersList = [];
  41447. }
  41448. }
  41449. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41450. if (!defines["LIGHT" + lightIndex]) {
  41451. break;
  41452. }
  41453. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41454. if (uniformBuffersList) {
  41455. uniformBuffersList.push("Light" + lightIndex);
  41456. }
  41457. samplersList.push("shadowSampler" + lightIndex);
  41458. samplersList.push("depthSampler" + lightIndex);
  41459. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41460. samplersList.push("projectionLightSampler" + lightIndex);
  41461. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41462. }
  41463. }
  41464. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41465. uniformsList.push("morphTargetInfluences");
  41466. }
  41467. };
  41468. /**
  41469. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41470. * @param defines The defines to update while falling back
  41471. * @param fallbacks The authorized effect fallbacks
  41472. * @param maxSimultaneousLights The maximum number of lights allowed
  41473. * @param rank the current rank of the Effect
  41474. * @returns The newly affected rank
  41475. */
  41476. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41477. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41478. if (rank === void 0) { rank = 0; }
  41479. var lightFallbackRank = 0;
  41480. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41481. if (!defines["LIGHT" + lightIndex]) {
  41482. break;
  41483. }
  41484. if (lightIndex > 0) {
  41485. lightFallbackRank = rank + lightIndex;
  41486. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41487. }
  41488. if (!defines["SHADOWS"]) {
  41489. if (defines["SHADOW" + lightIndex]) {
  41490. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41491. }
  41492. if (defines["SHADOWPCF" + lightIndex]) {
  41493. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41494. }
  41495. if (defines["SHADOWPCSS" + lightIndex]) {
  41496. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41497. }
  41498. if (defines["SHADOWPOISSON" + lightIndex]) {
  41499. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41500. }
  41501. if (defines["SHADOWESM" + lightIndex]) {
  41502. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41503. }
  41504. }
  41505. }
  41506. return lightFallbackRank++;
  41507. };
  41508. /**
  41509. * Prepares the list of attributes required for morph targets according to the effect defines.
  41510. * @param attribs The current list of supported attribs
  41511. * @param mesh The mesh to prepare the morph targets attributes for
  41512. * @param defines The current Defines of the effect
  41513. */
  41514. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41515. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41516. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41517. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41518. var manager = mesh.morphTargetManager;
  41519. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41520. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41521. for (var index = 0; index < influencers; index++) {
  41522. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41523. if (normal) {
  41524. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41525. }
  41526. if (tangent) {
  41527. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41528. }
  41529. if (attribs.length > maxAttributesCount) {
  41530. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41531. }
  41532. }
  41533. }
  41534. };
  41535. /**
  41536. * Prepares the list of attributes required for bones according to the effect defines.
  41537. * @param attribs The current list of supported attribs
  41538. * @param mesh The mesh to prepare the bones attributes for
  41539. * @param defines The current Defines of the effect
  41540. * @param fallbacks The current efffect fallback strategy
  41541. */
  41542. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41543. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41544. fallbacks.addCPUSkinningFallback(0, mesh);
  41545. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41546. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41547. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41548. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41549. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41550. }
  41551. }
  41552. };
  41553. /**
  41554. * Prepares the list of attributes required for instances according to the effect defines.
  41555. * @param attribs The current list of supported attribs
  41556. * @param defines The current Defines of the effect
  41557. */
  41558. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41559. if (defines["INSTANCES"]) {
  41560. attribs.push("world0");
  41561. attribs.push("world1");
  41562. attribs.push("world2");
  41563. attribs.push("world3");
  41564. }
  41565. };
  41566. /**
  41567. * Binds the light shadow information to the effect for the given mesh.
  41568. * @param light The light containing the generator
  41569. * @param scene The scene the lights belongs to
  41570. * @param mesh The mesh we are binding the information to render
  41571. * @param lightIndex The light index in the effect used to render the mesh
  41572. * @param effect The effect we are binding the data to
  41573. */
  41574. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41575. if (light.shadowEnabled && mesh.receiveShadows) {
  41576. var shadowGenerator = light.getShadowGenerator();
  41577. if (shadowGenerator) {
  41578. shadowGenerator.bindShadowLight(lightIndex, effect);
  41579. }
  41580. }
  41581. };
  41582. /**
  41583. * Binds the light information to the effect.
  41584. * @param light The light containing the generator
  41585. * @param effect The effect we are binding the data to
  41586. * @param lightIndex The light index in the effect used to render
  41587. */
  41588. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41589. light.transferToEffect(effect, lightIndex + "");
  41590. };
  41591. /**
  41592. * Binds the lights information from the scene to the effect for the given mesh.
  41593. * @param scene The scene the lights belongs to
  41594. * @param mesh The mesh we are binding the information to render
  41595. * @param effect The effect we are binding the data to
  41596. * @param defines The generated defines for the effect
  41597. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41598. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41599. */
  41600. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41601. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41602. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41603. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41604. for (var i = 0; i < len; i++) {
  41605. var light = mesh._lightSources[i];
  41606. var iAsString = i.toString();
  41607. var scaledIntensity = light.getScaledIntensity();
  41608. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41609. MaterialHelper.BindLightProperties(light, effect, i);
  41610. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41611. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41612. if (defines["SPECULARTERM"]) {
  41613. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41614. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41615. }
  41616. // Shadows
  41617. if (scene.shadowsEnabled) {
  41618. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41619. }
  41620. light._uniformBuffer.update();
  41621. }
  41622. };
  41623. /**
  41624. * Binds the fog information from the scene to the effect for the given mesh.
  41625. * @param scene The scene the lights belongs to
  41626. * @param mesh The mesh we are binding the information to render
  41627. * @param effect The effect we are binding the data to
  41628. */
  41629. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41630. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41631. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41632. effect.setColor3("vFogColor", scene.fogColor);
  41633. }
  41634. };
  41635. /**
  41636. * Binds the bones information from the mesh to the effect.
  41637. * @param mesh The mesh we are binding the information to render
  41638. * @param effect The effect we are binding the data to
  41639. */
  41640. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41641. if (!effect || !mesh) {
  41642. return;
  41643. }
  41644. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41645. mesh.computeBonesUsingShaders = false;
  41646. }
  41647. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41648. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41649. if (matrices) {
  41650. effect.setMatrices("mBones", matrices);
  41651. }
  41652. }
  41653. };
  41654. /**
  41655. * Binds the morph targets information from the mesh to the effect.
  41656. * @param abstractMesh The mesh we are binding the information to render
  41657. * @param effect The effect we are binding the data to
  41658. */
  41659. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41660. var manager = abstractMesh.morphTargetManager;
  41661. if (!abstractMesh || !manager) {
  41662. return;
  41663. }
  41664. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41665. };
  41666. /**
  41667. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41668. * @param defines The generated defines used in the effect
  41669. * @param effect The effect we are binding the data to
  41670. * @param scene The scene we are willing to render with logarithmic scale for
  41671. */
  41672. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41673. if (defines["LOGARITHMICDEPTH"]) {
  41674. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41675. }
  41676. };
  41677. /**
  41678. * Binds the clip plane information from the scene to the effect.
  41679. * @param scene The scene the clip plane information are extracted from
  41680. * @param effect The effect we are binding the data to
  41681. */
  41682. MaterialHelper.BindClipPlane = function (effect, scene) {
  41683. if (scene.clipPlane) {
  41684. var clipPlane = scene.clipPlane;
  41685. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41686. }
  41687. };
  41688. return MaterialHelper;
  41689. }());
  41690. BABYLON.MaterialHelper = MaterialHelper;
  41691. })(BABYLON || (BABYLON = {}));
  41692. //# sourceMappingURL=babylon.materialHelper.js.map
  41693. var BABYLON;
  41694. (function (BABYLON) {
  41695. var PushMaterial = /** @class */ (function (_super) {
  41696. __extends(PushMaterial, _super);
  41697. function PushMaterial(name, scene) {
  41698. var _this = _super.call(this, name, scene) || this;
  41699. _this._normalMatrix = new BABYLON.Matrix();
  41700. _this.storeEffectOnSubMeshes = true;
  41701. return _this;
  41702. }
  41703. PushMaterial.prototype.getEffect = function () {
  41704. return this._activeEffect;
  41705. };
  41706. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41707. if (!mesh) {
  41708. return false;
  41709. }
  41710. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41711. return true;
  41712. }
  41713. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41714. };
  41715. /**
  41716. * Binds the given world matrix to the active effect
  41717. *
  41718. * @param world the matrix to bind
  41719. */
  41720. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41721. this._activeEffect.setMatrix("world", world);
  41722. };
  41723. /**
  41724. * Binds the given normal matrix to the active effect
  41725. *
  41726. * @param normalMatrix the matrix to bind
  41727. */
  41728. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41729. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41730. };
  41731. PushMaterial.prototype.bind = function (world, mesh) {
  41732. if (!mesh) {
  41733. return;
  41734. }
  41735. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41736. };
  41737. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41738. if (effect === void 0) { effect = null; }
  41739. _super.prototype._afterBind.call(this, mesh);
  41740. this.getScene()._cachedEffect = effect;
  41741. };
  41742. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41743. if (visibility === void 0) { visibility = 1; }
  41744. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41745. };
  41746. return PushMaterial;
  41747. }(BABYLON.Material));
  41748. BABYLON.PushMaterial = PushMaterial;
  41749. })(BABYLON || (BABYLON = {}));
  41750. //# sourceMappingURL=babylon.pushMaterial.js.map
  41751. var BABYLON;
  41752. (function (BABYLON) {
  41753. /** @hidden */
  41754. var StandardMaterialDefines = /** @class */ (function (_super) {
  41755. __extends(StandardMaterialDefines, _super);
  41756. function StandardMaterialDefines() {
  41757. var _this = _super.call(this) || this;
  41758. _this.MAINUV1 = false;
  41759. _this.MAINUV2 = false;
  41760. _this.DIFFUSE = false;
  41761. _this.DIFFUSEDIRECTUV = 0;
  41762. _this.AMBIENT = false;
  41763. _this.AMBIENTDIRECTUV = 0;
  41764. _this.OPACITY = false;
  41765. _this.OPACITYDIRECTUV = 0;
  41766. _this.OPACITYRGB = false;
  41767. _this.REFLECTION = false;
  41768. _this.EMISSIVE = false;
  41769. _this.EMISSIVEDIRECTUV = 0;
  41770. _this.SPECULAR = false;
  41771. _this.SPECULARDIRECTUV = 0;
  41772. _this.BUMP = false;
  41773. _this.BUMPDIRECTUV = 0;
  41774. _this.PARALLAX = false;
  41775. _this.PARALLAXOCCLUSION = false;
  41776. _this.SPECULAROVERALPHA = false;
  41777. _this.CLIPPLANE = false;
  41778. _this.ALPHATEST = false;
  41779. _this.DEPTHPREPASS = false;
  41780. _this.ALPHAFROMDIFFUSE = false;
  41781. _this.POINTSIZE = false;
  41782. _this.FOG = false;
  41783. _this.SPECULARTERM = false;
  41784. _this.DIFFUSEFRESNEL = false;
  41785. _this.OPACITYFRESNEL = false;
  41786. _this.REFLECTIONFRESNEL = false;
  41787. _this.REFRACTIONFRESNEL = false;
  41788. _this.EMISSIVEFRESNEL = false;
  41789. _this.FRESNEL = false;
  41790. _this.NORMAL = false;
  41791. _this.UV1 = false;
  41792. _this.UV2 = false;
  41793. _this.VERTEXCOLOR = false;
  41794. _this.VERTEXALPHA = false;
  41795. _this.NUM_BONE_INFLUENCERS = 0;
  41796. _this.BonesPerMesh = 0;
  41797. _this.INSTANCES = false;
  41798. _this.GLOSSINESS = false;
  41799. _this.ROUGHNESS = false;
  41800. _this.EMISSIVEASILLUMINATION = false;
  41801. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41802. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41803. _this.LIGHTMAP = false;
  41804. _this.LIGHTMAPDIRECTUV = 0;
  41805. _this.OBJECTSPACE_NORMALMAP = false;
  41806. _this.USELIGHTMAPASSHADOWMAP = false;
  41807. _this.REFLECTIONMAP_3D = false;
  41808. _this.REFLECTIONMAP_SPHERICAL = false;
  41809. _this.REFLECTIONMAP_PLANAR = false;
  41810. _this.REFLECTIONMAP_CUBIC = false;
  41811. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41812. _this.REFLECTIONMAP_PROJECTION = false;
  41813. _this.REFLECTIONMAP_SKYBOX = false;
  41814. _this.REFLECTIONMAP_EXPLICIT = false;
  41815. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41816. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41817. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41818. _this.INVERTCUBICMAP = false;
  41819. _this.LOGARITHMICDEPTH = false;
  41820. _this.REFRACTION = false;
  41821. _this.REFRACTIONMAP_3D = false;
  41822. _this.REFLECTIONOVERALPHA = false;
  41823. _this.TWOSIDEDLIGHTING = false;
  41824. _this.SHADOWFLOAT = false;
  41825. _this.MORPHTARGETS = false;
  41826. _this.MORPHTARGETS_NORMAL = false;
  41827. _this.MORPHTARGETS_TANGENT = false;
  41828. _this.NUM_MORPH_INFLUENCERS = 0;
  41829. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41830. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41831. _this.IMAGEPROCESSING = false;
  41832. _this.VIGNETTE = false;
  41833. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41834. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41835. _this.TONEMAPPING = false;
  41836. _this.CONTRAST = false;
  41837. _this.COLORCURVES = false;
  41838. _this.COLORGRADING = false;
  41839. _this.COLORGRADING3D = false;
  41840. _this.SAMPLER3DGREENDEPTH = false;
  41841. _this.SAMPLER3DBGRMAP = false;
  41842. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41843. /**
  41844. * If the reflection texture on this material is in linear color space
  41845. * @hidden
  41846. */
  41847. _this.IS_REFLECTION_LINEAR = false;
  41848. /**
  41849. * If the refraction texture on this material is in linear color space
  41850. * @hidden
  41851. */
  41852. _this.IS_REFRACTION_LINEAR = false;
  41853. _this.EXPOSURE = false;
  41854. _this.rebuild();
  41855. return _this;
  41856. }
  41857. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41858. var modes = [
  41859. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41860. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41861. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41862. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41863. ];
  41864. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41865. var mode = modes_1[_i];
  41866. this[mode] = (mode === modeToEnable);
  41867. }
  41868. };
  41869. return StandardMaterialDefines;
  41870. }(BABYLON.MaterialDefines));
  41871. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41872. var StandardMaterial = /** @class */ (function (_super) {
  41873. __extends(StandardMaterial, _super);
  41874. function StandardMaterial(name, scene) {
  41875. var _this = _super.call(this, name, scene) || this;
  41876. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41877. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41878. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41879. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41880. _this.specularPower = 64;
  41881. _this._useAlphaFromDiffuseTexture = false;
  41882. _this._useEmissiveAsIllumination = false;
  41883. _this._linkEmissiveWithDiffuse = false;
  41884. _this._useSpecularOverAlpha = false;
  41885. _this._useReflectionOverAlpha = false;
  41886. _this._disableLighting = false;
  41887. _this._useObjectSpaceNormalMap = false;
  41888. _this._useParallax = false;
  41889. _this._useParallaxOcclusion = false;
  41890. _this.parallaxScaleBias = 0.05;
  41891. _this._roughness = 0;
  41892. _this.indexOfRefraction = 0.98;
  41893. _this.invertRefractionY = true;
  41894. /**
  41895. * Defines the alpha limits in alpha test mode
  41896. */
  41897. _this.alphaCutOff = 0.4;
  41898. _this._useLightmapAsShadowmap = false;
  41899. _this._useReflectionFresnelFromSpecular = false;
  41900. _this._useGlossinessFromSpecularMapAlpha = false;
  41901. _this._maxSimultaneousLights = 4;
  41902. /**
  41903. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41904. */
  41905. _this._invertNormalMapX = false;
  41906. /**
  41907. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41908. */
  41909. _this._invertNormalMapY = false;
  41910. /**
  41911. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41912. */
  41913. _this._twoSidedLighting = false;
  41914. _this._renderTargets = new BABYLON.SmartArray(16);
  41915. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41916. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41917. // Setup the default processing configuration to the scene.
  41918. _this._attachImageProcessingConfiguration(null);
  41919. _this.getRenderTargetTextures = function () {
  41920. _this._renderTargets.reset();
  41921. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41922. _this._renderTargets.push(_this._reflectionTexture);
  41923. }
  41924. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41925. _this._renderTargets.push(_this._refractionTexture);
  41926. }
  41927. return _this._renderTargets;
  41928. };
  41929. return _this;
  41930. }
  41931. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41932. /**
  41933. * Gets the image processing configuration used either in this material.
  41934. */
  41935. get: function () {
  41936. return this._imageProcessingConfiguration;
  41937. },
  41938. /**
  41939. * Sets the Default image processing configuration used either in the this material.
  41940. *
  41941. * If sets to null, the scene one is in use.
  41942. */
  41943. set: function (value) {
  41944. this._attachImageProcessingConfiguration(value);
  41945. // Ensure the effect will be rebuilt.
  41946. this._markAllSubMeshesAsTexturesDirty();
  41947. },
  41948. enumerable: true,
  41949. configurable: true
  41950. });
  41951. /**
  41952. * Attaches a new image processing configuration to the Standard Material.
  41953. * @param configuration
  41954. */
  41955. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41956. var _this = this;
  41957. if (configuration === this._imageProcessingConfiguration) {
  41958. return;
  41959. }
  41960. // Detaches observer.
  41961. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41962. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41963. }
  41964. // Pick the scene configuration if needed.
  41965. if (!configuration) {
  41966. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41967. }
  41968. else {
  41969. this._imageProcessingConfiguration = configuration;
  41970. }
  41971. // Attaches observer.
  41972. if (this._imageProcessingConfiguration) {
  41973. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41974. _this._markAllSubMeshesAsImageProcessingDirty();
  41975. });
  41976. }
  41977. };
  41978. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41979. /**
  41980. * Gets wether the color curves effect is enabled.
  41981. */
  41982. get: function () {
  41983. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41984. },
  41985. /**
  41986. * Sets wether the color curves effect is enabled.
  41987. */
  41988. set: function (value) {
  41989. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41990. },
  41991. enumerable: true,
  41992. configurable: true
  41993. });
  41994. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41995. /**
  41996. * Gets wether the color grading effect is enabled.
  41997. */
  41998. get: function () {
  41999. return this.imageProcessingConfiguration.colorGradingEnabled;
  42000. },
  42001. /**
  42002. * Gets wether the color grading effect is enabled.
  42003. */
  42004. set: function (value) {
  42005. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42006. },
  42007. enumerable: true,
  42008. configurable: true
  42009. });
  42010. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42011. /**
  42012. * Gets wether tonemapping is enabled or not.
  42013. */
  42014. get: function () {
  42015. return this._imageProcessingConfiguration.toneMappingEnabled;
  42016. },
  42017. /**
  42018. * Sets wether tonemapping is enabled or not
  42019. */
  42020. set: function (value) {
  42021. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42022. },
  42023. enumerable: true,
  42024. configurable: true
  42025. });
  42026. ;
  42027. ;
  42028. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42029. /**
  42030. * The camera exposure used on this material.
  42031. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42032. * This corresponds to a photographic exposure.
  42033. */
  42034. get: function () {
  42035. return this._imageProcessingConfiguration.exposure;
  42036. },
  42037. /**
  42038. * The camera exposure used on this material.
  42039. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42040. * This corresponds to a photographic exposure.
  42041. */
  42042. set: function (value) {
  42043. this._imageProcessingConfiguration.exposure = value;
  42044. },
  42045. enumerable: true,
  42046. configurable: true
  42047. });
  42048. ;
  42049. ;
  42050. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42051. /**
  42052. * Gets The camera contrast used on this material.
  42053. */
  42054. get: function () {
  42055. return this._imageProcessingConfiguration.contrast;
  42056. },
  42057. /**
  42058. * Sets The camera contrast used on this material.
  42059. */
  42060. set: function (value) {
  42061. this._imageProcessingConfiguration.contrast = value;
  42062. },
  42063. enumerable: true,
  42064. configurable: true
  42065. });
  42066. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42067. /**
  42068. * Gets the Color Grading 2D Lookup Texture.
  42069. */
  42070. get: function () {
  42071. return this._imageProcessingConfiguration.colorGradingTexture;
  42072. },
  42073. /**
  42074. * Sets the Color Grading 2D Lookup Texture.
  42075. */
  42076. set: function (value) {
  42077. this._imageProcessingConfiguration.colorGradingTexture = value;
  42078. },
  42079. enumerable: true,
  42080. configurable: true
  42081. });
  42082. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42083. /**
  42084. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42085. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42086. * 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;
  42087. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42088. */
  42089. get: function () {
  42090. return this._imageProcessingConfiguration.colorCurves;
  42091. },
  42092. /**
  42093. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42094. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42095. * 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;
  42096. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42097. */
  42098. set: function (value) {
  42099. this._imageProcessingConfiguration.colorCurves = value;
  42100. },
  42101. enumerable: true,
  42102. configurable: true
  42103. });
  42104. StandardMaterial.prototype.getClassName = function () {
  42105. return "StandardMaterial";
  42106. };
  42107. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42108. get: function () {
  42109. return this._useLogarithmicDepth;
  42110. },
  42111. set: function (value) {
  42112. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42113. this._markAllSubMeshesAsMiscDirty();
  42114. },
  42115. enumerable: true,
  42116. configurable: true
  42117. });
  42118. StandardMaterial.prototype.needAlphaBlending = function () {
  42119. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42120. };
  42121. StandardMaterial.prototype.needAlphaTesting = function () {
  42122. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42123. };
  42124. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42125. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42126. };
  42127. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42128. return this._diffuseTexture;
  42129. };
  42130. /**
  42131. * Child classes can use it to update shaders
  42132. */
  42133. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42134. if (useInstances === void 0) { useInstances = false; }
  42135. if (subMesh.effect && this.isFrozen) {
  42136. if (this._wasPreviouslyReady && subMesh.effect) {
  42137. return true;
  42138. }
  42139. }
  42140. if (!subMesh._materialDefines) {
  42141. subMesh._materialDefines = new StandardMaterialDefines();
  42142. }
  42143. var scene = this.getScene();
  42144. var defines = subMesh._materialDefines;
  42145. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42146. if (defines._renderId === scene.getRenderId()) {
  42147. return true;
  42148. }
  42149. }
  42150. var engine = scene.getEngine();
  42151. // Lights
  42152. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42153. // Textures
  42154. if (defines._areTexturesDirty) {
  42155. defines._needUVs = false;
  42156. defines.MAINUV1 = false;
  42157. defines.MAINUV2 = false;
  42158. if (scene.texturesEnabled) {
  42159. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42160. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42161. return false;
  42162. }
  42163. else {
  42164. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42165. }
  42166. }
  42167. else {
  42168. defines.DIFFUSE = false;
  42169. }
  42170. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42171. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42172. return false;
  42173. }
  42174. else {
  42175. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42176. }
  42177. }
  42178. else {
  42179. defines.AMBIENT = false;
  42180. }
  42181. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42182. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42183. return false;
  42184. }
  42185. else {
  42186. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42187. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42188. }
  42189. }
  42190. else {
  42191. defines.OPACITY = false;
  42192. }
  42193. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42194. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42195. return false;
  42196. }
  42197. else {
  42198. defines._needNormals = true;
  42199. defines.REFLECTION = true;
  42200. defines.ROUGHNESS = (this._roughness > 0);
  42201. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42202. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42203. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42204. switch (this._reflectionTexture.coordinatesMode) {
  42205. case BABYLON.Texture.EXPLICIT_MODE:
  42206. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42207. break;
  42208. case BABYLON.Texture.PLANAR_MODE:
  42209. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42210. break;
  42211. case BABYLON.Texture.PROJECTION_MODE:
  42212. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42213. break;
  42214. case BABYLON.Texture.SKYBOX_MODE:
  42215. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42216. break;
  42217. case BABYLON.Texture.SPHERICAL_MODE:
  42218. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42219. break;
  42220. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42221. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42222. break;
  42223. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42224. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42225. break;
  42226. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42227. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42228. break;
  42229. case BABYLON.Texture.CUBIC_MODE:
  42230. case BABYLON.Texture.INVCUBIC_MODE:
  42231. default:
  42232. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42233. break;
  42234. }
  42235. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42236. }
  42237. }
  42238. else {
  42239. defines.REFLECTION = false;
  42240. }
  42241. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42242. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42243. return false;
  42244. }
  42245. else {
  42246. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42247. }
  42248. }
  42249. else {
  42250. defines.EMISSIVE = false;
  42251. }
  42252. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42253. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42254. return false;
  42255. }
  42256. else {
  42257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42258. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42259. }
  42260. }
  42261. else {
  42262. defines.LIGHTMAP = false;
  42263. }
  42264. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42265. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42266. return false;
  42267. }
  42268. else {
  42269. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42270. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42271. }
  42272. }
  42273. else {
  42274. defines.SPECULAR = false;
  42275. }
  42276. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42277. // Bump texure can not be not blocking.
  42278. if (!this._bumpTexture.isReady()) {
  42279. return false;
  42280. }
  42281. else {
  42282. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42283. defines.PARALLAX = this._useParallax;
  42284. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42285. }
  42286. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42287. }
  42288. else {
  42289. defines.BUMP = false;
  42290. }
  42291. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42292. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42293. return false;
  42294. }
  42295. else {
  42296. defines._needUVs = true;
  42297. defines.REFRACTION = true;
  42298. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42299. }
  42300. }
  42301. else {
  42302. defines.REFRACTION = false;
  42303. }
  42304. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42305. }
  42306. else {
  42307. defines.DIFFUSE = false;
  42308. defines.AMBIENT = false;
  42309. defines.OPACITY = false;
  42310. defines.REFLECTION = false;
  42311. defines.EMISSIVE = false;
  42312. defines.LIGHTMAP = false;
  42313. defines.BUMP = false;
  42314. defines.REFRACTION = false;
  42315. }
  42316. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42317. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42318. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42319. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42320. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42321. }
  42322. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42323. if (!this._imageProcessingConfiguration.isReady()) {
  42324. return false;
  42325. }
  42326. this._imageProcessingConfiguration.prepareDefines(defines);
  42327. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42328. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42329. }
  42330. if (defines._areFresnelDirty) {
  42331. if (StandardMaterial.FresnelEnabled) {
  42332. // Fresnel
  42333. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42334. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42335. this._reflectionFresnelParameters) {
  42336. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42337. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42338. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42339. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42340. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42341. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42342. defines._needNormals = true;
  42343. defines.FRESNEL = true;
  42344. }
  42345. }
  42346. else {
  42347. defines.FRESNEL = false;
  42348. }
  42349. }
  42350. // Misc.
  42351. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42352. // Attribs
  42353. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42354. // Values that need to be evaluated on every frame
  42355. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42356. // Get correct effect
  42357. if (defines.isDirty) {
  42358. defines.markAsProcessed();
  42359. scene.resetCachedMaterial();
  42360. // Fallbacks
  42361. var fallbacks = new BABYLON.EffectFallbacks();
  42362. if (defines.REFLECTION) {
  42363. fallbacks.addFallback(0, "REFLECTION");
  42364. }
  42365. if (defines.SPECULAR) {
  42366. fallbacks.addFallback(0, "SPECULAR");
  42367. }
  42368. if (defines.BUMP) {
  42369. fallbacks.addFallback(0, "BUMP");
  42370. }
  42371. if (defines.PARALLAX) {
  42372. fallbacks.addFallback(1, "PARALLAX");
  42373. }
  42374. if (defines.PARALLAXOCCLUSION) {
  42375. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42376. }
  42377. if (defines.SPECULAROVERALPHA) {
  42378. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42379. }
  42380. if (defines.FOG) {
  42381. fallbacks.addFallback(1, "FOG");
  42382. }
  42383. if (defines.POINTSIZE) {
  42384. fallbacks.addFallback(0, "POINTSIZE");
  42385. }
  42386. if (defines.LOGARITHMICDEPTH) {
  42387. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42388. }
  42389. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42390. if (defines.SPECULARTERM) {
  42391. fallbacks.addFallback(0, "SPECULARTERM");
  42392. }
  42393. if (defines.DIFFUSEFRESNEL) {
  42394. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42395. }
  42396. if (defines.OPACITYFRESNEL) {
  42397. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42398. }
  42399. if (defines.REFLECTIONFRESNEL) {
  42400. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42401. }
  42402. if (defines.EMISSIVEFRESNEL) {
  42403. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42404. }
  42405. if (defines.FRESNEL) {
  42406. fallbacks.addFallback(4, "FRESNEL");
  42407. }
  42408. //Attributes
  42409. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42410. if (defines.NORMAL) {
  42411. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42412. }
  42413. if (defines.UV1) {
  42414. attribs.push(BABYLON.VertexBuffer.UVKind);
  42415. }
  42416. if (defines.UV2) {
  42417. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42418. }
  42419. if (defines.VERTEXCOLOR) {
  42420. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42421. }
  42422. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42423. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42424. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42425. var shaderName = "default";
  42426. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42427. "vFogInfos", "vFogColor", "pointSize",
  42428. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42429. "mBones",
  42430. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42431. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42432. "vReflectionPosition", "vReflectionSize",
  42433. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42434. ];
  42435. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42436. var uniformBuffers = ["Material", "Scene"];
  42437. if (BABYLON.ImageProcessingConfiguration) {
  42438. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42439. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42440. }
  42441. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42442. uniformsNames: uniforms,
  42443. uniformBuffersNames: uniformBuffers,
  42444. samplers: samplers,
  42445. defines: defines,
  42446. maxSimultaneousLights: this._maxSimultaneousLights
  42447. });
  42448. if (this.customShaderNameResolve) {
  42449. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42450. }
  42451. var join = defines.toString();
  42452. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42453. attributes: attribs,
  42454. uniformsNames: uniforms,
  42455. uniformBuffersNames: uniformBuffers,
  42456. samplers: samplers,
  42457. defines: join,
  42458. fallbacks: fallbacks,
  42459. onCompiled: this.onCompiled,
  42460. onError: this.onError,
  42461. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42462. }, engine), defines);
  42463. this.buildUniformLayout();
  42464. }
  42465. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42466. return false;
  42467. }
  42468. defines._renderId = scene.getRenderId();
  42469. this._wasPreviouslyReady = true;
  42470. return true;
  42471. };
  42472. StandardMaterial.prototype.buildUniformLayout = function () {
  42473. // Order is important !
  42474. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42475. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42476. this._uniformBuffer.addUniform("opacityParts", 4);
  42477. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42478. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42479. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42480. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42481. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42482. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42483. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42484. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42485. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42486. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42487. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42488. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42489. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42490. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42491. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42492. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42493. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42494. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42495. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42496. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42497. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42498. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42499. this._uniformBuffer.addUniform("specularMatrix", 16);
  42500. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42501. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42502. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42503. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42504. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42505. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42506. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42507. this._uniformBuffer.addUniform("pointSize", 1);
  42508. this._uniformBuffer.create();
  42509. };
  42510. StandardMaterial.prototype.unbind = function () {
  42511. if (this._activeEffect) {
  42512. var needFlag = false;
  42513. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42514. this._activeEffect.setTexture("reflection2DSampler", null);
  42515. needFlag = true;
  42516. }
  42517. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42518. this._activeEffect.setTexture("refraction2DSampler", null);
  42519. needFlag = true;
  42520. }
  42521. if (needFlag) {
  42522. this._markAllSubMeshesAsTexturesDirty();
  42523. }
  42524. }
  42525. _super.prototype.unbind.call(this);
  42526. };
  42527. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42528. var scene = this.getScene();
  42529. var defines = subMesh._materialDefines;
  42530. if (!defines) {
  42531. return;
  42532. }
  42533. var effect = subMesh.effect;
  42534. if (!effect) {
  42535. return;
  42536. }
  42537. this._activeEffect = effect;
  42538. // Matrices
  42539. this.bindOnlyWorldMatrix(world);
  42540. // Normal Matrix
  42541. if (defines.OBJECTSPACE_NORMALMAP) {
  42542. world.toNormalMatrix(this._normalMatrix);
  42543. this.bindOnlyNormalMatrix(this._normalMatrix);
  42544. }
  42545. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42546. // Bones
  42547. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42548. if (mustRebind) {
  42549. this._uniformBuffer.bindToEffect(effect, "Material");
  42550. this.bindViewProjection(effect);
  42551. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42552. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42553. // Fresnel
  42554. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42555. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42556. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42557. }
  42558. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42559. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42560. }
  42561. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42562. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42563. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42564. }
  42565. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42566. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42567. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42568. }
  42569. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42570. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42571. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42572. }
  42573. }
  42574. // Textures
  42575. if (scene.texturesEnabled) {
  42576. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42577. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42578. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42579. if (this._diffuseTexture.hasAlpha) {
  42580. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42581. }
  42582. }
  42583. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42584. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42585. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42586. }
  42587. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42588. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42589. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42590. }
  42591. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42592. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42593. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42594. if (this._reflectionTexture.boundingBoxSize) {
  42595. var cubeTexture = this._reflectionTexture;
  42596. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42597. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42598. }
  42599. }
  42600. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42601. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42602. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42603. }
  42604. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42605. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42606. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42607. }
  42608. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42609. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42610. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42611. }
  42612. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42613. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42614. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42615. if (scene._mirroredCameraPosition) {
  42616. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42617. }
  42618. else {
  42619. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42620. }
  42621. }
  42622. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42623. var depth = 1.0;
  42624. if (!this._refractionTexture.isCube) {
  42625. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42626. if (this._refractionTexture.depth) {
  42627. depth = this._refractionTexture.depth;
  42628. }
  42629. }
  42630. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42631. }
  42632. }
  42633. // Point size
  42634. if (this.pointsCloud) {
  42635. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42636. }
  42637. if (defines.SPECULARTERM) {
  42638. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42639. }
  42640. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42641. // Diffuse
  42642. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42643. }
  42644. // Textures
  42645. if (scene.texturesEnabled) {
  42646. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42647. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42648. }
  42649. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42650. effect.setTexture("ambientSampler", this._ambientTexture);
  42651. }
  42652. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42653. effect.setTexture("opacitySampler", this._opacityTexture);
  42654. }
  42655. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42656. if (this._reflectionTexture.isCube) {
  42657. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42658. }
  42659. else {
  42660. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42661. }
  42662. }
  42663. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42664. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42665. }
  42666. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42667. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42668. }
  42669. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42670. effect.setTexture("specularSampler", this._specularTexture);
  42671. }
  42672. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42673. effect.setTexture("bumpSampler", this._bumpTexture);
  42674. }
  42675. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42676. var depth = 1.0;
  42677. if (this._refractionTexture.isCube) {
  42678. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42679. }
  42680. else {
  42681. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42682. }
  42683. }
  42684. }
  42685. // Clip plane
  42686. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42687. // Colors
  42688. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42689. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42690. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42691. }
  42692. if (mustRebind || !this.isFrozen) {
  42693. // Lights
  42694. if (scene.lightsEnabled && !this._disableLighting) {
  42695. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42696. }
  42697. // View
  42698. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42699. this.bindView(effect);
  42700. }
  42701. // Fog
  42702. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42703. // Morph targets
  42704. if (defines.NUM_MORPH_INFLUENCERS) {
  42705. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42706. }
  42707. // Log. depth
  42708. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42709. // image processing
  42710. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42711. this._imageProcessingConfiguration.bind(this._activeEffect);
  42712. }
  42713. }
  42714. this._uniformBuffer.update();
  42715. this._afterBind(mesh, this._activeEffect);
  42716. };
  42717. StandardMaterial.prototype.getAnimatables = function () {
  42718. var results = [];
  42719. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42720. results.push(this._diffuseTexture);
  42721. }
  42722. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42723. results.push(this._ambientTexture);
  42724. }
  42725. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42726. results.push(this._opacityTexture);
  42727. }
  42728. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42729. results.push(this._reflectionTexture);
  42730. }
  42731. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42732. results.push(this._emissiveTexture);
  42733. }
  42734. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42735. results.push(this._specularTexture);
  42736. }
  42737. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42738. results.push(this._bumpTexture);
  42739. }
  42740. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42741. results.push(this._lightmapTexture);
  42742. }
  42743. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42744. results.push(this._refractionTexture);
  42745. }
  42746. return results;
  42747. };
  42748. StandardMaterial.prototype.getActiveTextures = function () {
  42749. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42750. if (this._diffuseTexture) {
  42751. activeTextures.push(this._diffuseTexture);
  42752. }
  42753. if (this._ambientTexture) {
  42754. activeTextures.push(this._ambientTexture);
  42755. }
  42756. if (this._opacityTexture) {
  42757. activeTextures.push(this._opacityTexture);
  42758. }
  42759. if (this._reflectionTexture) {
  42760. activeTextures.push(this._reflectionTexture);
  42761. }
  42762. if (this._emissiveTexture) {
  42763. activeTextures.push(this._emissiveTexture);
  42764. }
  42765. if (this._specularTexture) {
  42766. activeTextures.push(this._specularTexture);
  42767. }
  42768. if (this._bumpTexture) {
  42769. activeTextures.push(this._bumpTexture);
  42770. }
  42771. if (this._lightmapTexture) {
  42772. activeTextures.push(this._lightmapTexture);
  42773. }
  42774. if (this._refractionTexture) {
  42775. activeTextures.push(this._refractionTexture);
  42776. }
  42777. return activeTextures;
  42778. };
  42779. StandardMaterial.prototype.hasTexture = function (texture) {
  42780. if (_super.prototype.hasTexture.call(this, texture)) {
  42781. return true;
  42782. }
  42783. if (this._diffuseTexture === texture) {
  42784. return true;
  42785. }
  42786. if (this._ambientTexture === texture) {
  42787. return true;
  42788. }
  42789. if (this._opacityTexture === texture) {
  42790. return true;
  42791. }
  42792. if (this._reflectionTexture === texture) {
  42793. return true;
  42794. }
  42795. if (this._emissiveTexture === texture) {
  42796. return true;
  42797. }
  42798. if (this._specularTexture === texture) {
  42799. return true;
  42800. }
  42801. if (this._bumpTexture === texture) {
  42802. return true;
  42803. }
  42804. if (this._lightmapTexture === texture) {
  42805. return true;
  42806. }
  42807. if (this._refractionTexture === texture) {
  42808. return true;
  42809. }
  42810. return false;
  42811. };
  42812. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42813. if (forceDisposeTextures) {
  42814. if (this._diffuseTexture) {
  42815. this._diffuseTexture.dispose();
  42816. }
  42817. if (this._ambientTexture) {
  42818. this._ambientTexture.dispose();
  42819. }
  42820. if (this._opacityTexture) {
  42821. this._opacityTexture.dispose();
  42822. }
  42823. if (this._reflectionTexture) {
  42824. this._reflectionTexture.dispose();
  42825. }
  42826. if (this._emissiveTexture) {
  42827. this._emissiveTexture.dispose();
  42828. }
  42829. if (this._specularTexture) {
  42830. this._specularTexture.dispose();
  42831. }
  42832. if (this._bumpTexture) {
  42833. this._bumpTexture.dispose();
  42834. }
  42835. if (this._lightmapTexture) {
  42836. this._lightmapTexture.dispose();
  42837. }
  42838. if (this._refractionTexture) {
  42839. this._refractionTexture.dispose();
  42840. }
  42841. }
  42842. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42843. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42844. }
  42845. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42846. };
  42847. StandardMaterial.prototype.clone = function (name) {
  42848. var _this = this;
  42849. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42850. result.name = name;
  42851. result.id = name;
  42852. return result;
  42853. };
  42854. StandardMaterial.prototype.serialize = function () {
  42855. return BABYLON.SerializationHelper.Serialize(this);
  42856. };
  42857. // Statics
  42858. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42859. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42860. };
  42861. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42862. get: function () {
  42863. return StandardMaterial._DiffuseTextureEnabled;
  42864. },
  42865. set: function (value) {
  42866. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42867. return;
  42868. }
  42869. StandardMaterial._DiffuseTextureEnabled = value;
  42870. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42871. },
  42872. enumerable: true,
  42873. configurable: true
  42874. });
  42875. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42876. get: function () {
  42877. return StandardMaterial._AmbientTextureEnabled;
  42878. },
  42879. set: function (value) {
  42880. if (StandardMaterial._AmbientTextureEnabled === value) {
  42881. return;
  42882. }
  42883. StandardMaterial._AmbientTextureEnabled = value;
  42884. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42885. },
  42886. enumerable: true,
  42887. configurable: true
  42888. });
  42889. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42890. get: function () {
  42891. return StandardMaterial._OpacityTextureEnabled;
  42892. },
  42893. set: function (value) {
  42894. if (StandardMaterial._OpacityTextureEnabled === value) {
  42895. return;
  42896. }
  42897. StandardMaterial._OpacityTextureEnabled = value;
  42898. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42899. },
  42900. enumerable: true,
  42901. configurable: true
  42902. });
  42903. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42904. get: function () {
  42905. return StandardMaterial._ReflectionTextureEnabled;
  42906. },
  42907. set: function (value) {
  42908. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42909. return;
  42910. }
  42911. StandardMaterial._ReflectionTextureEnabled = value;
  42912. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42913. },
  42914. enumerable: true,
  42915. configurable: true
  42916. });
  42917. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42918. get: function () {
  42919. return StandardMaterial._EmissiveTextureEnabled;
  42920. },
  42921. set: function (value) {
  42922. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42923. return;
  42924. }
  42925. StandardMaterial._EmissiveTextureEnabled = value;
  42926. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42927. },
  42928. enumerable: true,
  42929. configurable: true
  42930. });
  42931. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42932. get: function () {
  42933. return StandardMaterial._SpecularTextureEnabled;
  42934. },
  42935. set: function (value) {
  42936. if (StandardMaterial._SpecularTextureEnabled === value) {
  42937. return;
  42938. }
  42939. StandardMaterial._SpecularTextureEnabled = value;
  42940. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42941. },
  42942. enumerable: true,
  42943. configurable: true
  42944. });
  42945. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42946. get: function () {
  42947. return StandardMaterial._BumpTextureEnabled;
  42948. },
  42949. set: function (value) {
  42950. if (StandardMaterial._BumpTextureEnabled === value) {
  42951. return;
  42952. }
  42953. StandardMaterial._BumpTextureEnabled = value;
  42954. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42960. get: function () {
  42961. return StandardMaterial._LightmapTextureEnabled;
  42962. },
  42963. set: function (value) {
  42964. if (StandardMaterial._LightmapTextureEnabled === value) {
  42965. return;
  42966. }
  42967. StandardMaterial._LightmapTextureEnabled = value;
  42968. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42969. },
  42970. enumerable: true,
  42971. configurable: true
  42972. });
  42973. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42974. get: function () {
  42975. return StandardMaterial._RefractionTextureEnabled;
  42976. },
  42977. set: function (value) {
  42978. if (StandardMaterial._RefractionTextureEnabled === value) {
  42979. return;
  42980. }
  42981. StandardMaterial._RefractionTextureEnabled = value;
  42982. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42983. },
  42984. enumerable: true,
  42985. configurable: true
  42986. });
  42987. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42988. get: function () {
  42989. return StandardMaterial._ColorGradingTextureEnabled;
  42990. },
  42991. set: function (value) {
  42992. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42993. return;
  42994. }
  42995. StandardMaterial._ColorGradingTextureEnabled = value;
  42996. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42997. },
  42998. enumerable: true,
  42999. configurable: true
  43000. });
  43001. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43002. get: function () {
  43003. return StandardMaterial._FresnelEnabled;
  43004. },
  43005. set: function (value) {
  43006. if (StandardMaterial._FresnelEnabled === value) {
  43007. return;
  43008. }
  43009. StandardMaterial._FresnelEnabled = value;
  43010. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43011. },
  43012. enumerable: true,
  43013. configurable: true
  43014. });
  43015. // Flags used to enable or disable a type of texture for all Standard Materials
  43016. StandardMaterial._DiffuseTextureEnabled = true;
  43017. StandardMaterial._AmbientTextureEnabled = true;
  43018. StandardMaterial._OpacityTextureEnabled = true;
  43019. StandardMaterial._ReflectionTextureEnabled = true;
  43020. StandardMaterial._EmissiveTextureEnabled = true;
  43021. StandardMaterial._SpecularTextureEnabled = true;
  43022. StandardMaterial._BumpTextureEnabled = true;
  43023. StandardMaterial._LightmapTextureEnabled = true;
  43024. StandardMaterial._RefractionTextureEnabled = true;
  43025. StandardMaterial._ColorGradingTextureEnabled = true;
  43026. StandardMaterial._FresnelEnabled = true;
  43027. __decorate([
  43028. BABYLON.serializeAsTexture("diffuseTexture")
  43029. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43030. __decorate([
  43031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43032. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43033. __decorate([
  43034. BABYLON.serializeAsTexture("ambientTexture")
  43035. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43036. __decorate([
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43038. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43039. __decorate([
  43040. BABYLON.serializeAsTexture("opacityTexture")
  43041. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43042. __decorate([
  43043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43044. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43045. __decorate([
  43046. BABYLON.serializeAsTexture("reflectionTexture")
  43047. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43048. __decorate([
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43051. __decorate([
  43052. BABYLON.serializeAsTexture("emissiveTexture")
  43053. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43054. __decorate([
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43056. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43057. __decorate([
  43058. BABYLON.serializeAsTexture("specularTexture")
  43059. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43060. __decorate([
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], StandardMaterial.prototype, "specularTexture", void 0);
  43063. __decorate([
  43064. BABYLON.serializeAsTexture("bumpTexture")
  43065. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43066. __decorate([
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43068. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsTexture("lightmapTexture")
  43071. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43072. __decorate([
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43075. __decorate([
  43076. BABYLON.serializeAsTexture("refractionTexture")
  43077. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43078. __decorate([
  43079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43080. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43081. __decorate([
  43082. BABYLON.serializeAsColor3("ambient")
  43083. ], StandardMaterial.prototype, "ambientColor", void 0);
  43084. __decorate([
  43085. BABYLON.serializeAsColor3("diffuse")
  43086. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43087. __decorate([
  43088. BABYLON.serializeAsColor3("specular")
  43089. ], StandardMaterial.prototype, "specularColor", void 0);
  43090. __decorate([
  43091. BABYLON.serializeAsColor3("emissive")
  43092. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43093. __decorate([
  43094. BABYLON.serialize()
  43095. ], StandardMaterial.prototype, "specularPower", void 0);
  43096. __decorate([
  43097. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43098. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43099. __decorate([
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43101. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43102. __decorate([
  43103. BABYLON.serialize("useEmissiveAsIllumination")
  43104. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43105. __decorate([
  43106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43107. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43108. __decorate([
  43109. BABYLON.serialize("linkEmissiveWithDiffuse")
  43110. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43111. __decorate([
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43114. __decorate([
  43115. BABYLON.serialize("useSpecularOverAlpha")
  43116. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43117. __decorate([
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43119. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43120. __decorate([
  43121. BABYLON.serialize("useReflectionOverAlpha")
  43122. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43123. __decorate([
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43125. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43126. __decorate([
  43127. BABYLON.serialize("disableLighting")
  43128. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43129. __decorate([
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43131. ], StandardMaterial.prototype, "disableLighting", void 0);
  43132. __decorate([
  43133. BABYLON.serialize("useObjectSpaceNormalMap")
  43134. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43135. __decorate([
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43138. __decorate([
  43139. BABYLON.serialize("useParallax")
  43140. ], StandardMaterial.prototype, "_useParallax", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], StandardMaterial.prototype, "useParallax", void 0);
  43144. __decorate([
  43145. BABYLON.serialize("useParallaxOcclusion")
  43146. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43147. __decorate([
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43150. __decorate([
  43151. BABYLON.serialize()
  43152. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43153. __decorate([
  43154. BABYLON.serialize("roughness")
  43155. ], StandardMaterial.prototype, "_roughness", void 0);
  43156. __decorate([
  43157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43158. ], StandardMaterial.prototype, "roughness", void 0);
  43159. __decorate([
  43160. BABYLON.serialize()
  43161. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43162. __decorate([
  43163. BABYLON.serialize()
  43164. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43165. __decorate([
  43166. BABYLON.serialize()
  43167. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43168. __decorate([
  43169. BABYLON.serialize("useLightmapAsShadowmap")
  43170. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43174. __decorate([
  43175. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43176. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43177. __decorate([
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43179. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43180. __decorate([
  43181. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43182. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43183. __decorate([
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43185. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43186. __decorate([
  43187. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43188. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43189. __decorate([
  43190. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43191. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43192. __decorate([
  43193. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43194. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43195. __decorate([
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43197. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43198. __decorate([
  43199. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43200. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43201. __decorate([
  43202. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43203. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43204. __decorate([
  43205. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43206. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43207. __decorate([
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43209. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43210. __decorate([
  43211. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43212. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43213. __decorate([
  43214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43215. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43216. __decorate([
  43217. BABYLON.serialize("maxSimultaneousLights")
  43218. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43219. __decorate([
  43220. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43221. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43222. __decorate([
  43223. BABYLON.serialize("invertNormalMapX")
  43224. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43225. __decorate([
  43226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43227. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43228. __decorate([
  43229. BABYLON.serialize("invertNormalMapY")
  43230. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43231. __decorate([
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43233. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43234. __decorate([
  43235. BABYLON.serialize("twoSidedLighting")
  43236. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43237. __decorate([
  43238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43239. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43240. __decorate([
  43241. BABYLON.serialize()
  43242. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43243. return StandardMaterial;
  43244. }(BABYLON.PushMaterial));
  43245. BABYLON.StandardMaterial = StandardMaterial;
  43246. })(BABYLON || (BABYLON = {}));
  43247. //# sourceMappingURL=babylon.standardMaterial.js.map
  43248. var BABYLON;
  43249. (function (BABYLON) {
  43250. /**
  43251. * Manages the defines for the PBR Material.
  43252. * @hiddenChildren
  43253. */
  43254. var PBRMaterialDefines = /** @class */ (function (_super) {
  43255. __extends(PBRMaterialDefines, _super);
  43256. /**
  43257. * Initializes the PBR Material defines.
  43258. */
  43259. function PBRMaterialDefines() {
  43260. var _this = _super.call(this) || this;
  43261. _this.PBR = true;
  43262. _this.MAINUV1 = false;
  43263. _this.MAINUV2 = false;
  43264. _this.UV1 = false;
  43265. _this.UV2 = false;
  43266. _this.ALBEDO = false;
  43267. _this.ALBEDODIRECTUV = 0;
  43268. _this.VERTEXCOLOR = false;
  43269. _this.AMBIENT = false;
  43270. _this.AMBIENTDIRECTUV = 0;
  43271. _this.AMBIENTINGRAYSCALE = false;
  43272. _this.OPACITY = false;
  43273. _this.VERTEXALPHA = false;
  43274. _this.OPACITYDIRECTUV = 0;
  43275. _this.OPACITYRGB = false;
  43276. _this.ALPHATEST = false;
  43277. _this.DEPTHPREPASS = false;
  43278. _this.ALPHABLEND = false;
  43279. _this.ALPHAFROMALBEDO = false;
  43280. _this.ALPHATESTVALUE = "0.5";
  43281. _this.SPECULAROVERALPHA = false;
  43282. _this.RADIANCEOVERALPHA = false;
  43283. _this.ALPHAFRESNEL = false;
  43284. _this.LINEARALPHAFRESNEL = false;
  43285. _this.PREMULTIPLYALPHA = false;
  43286. _this.EMISSIVE = false;
  43287. _this.EMISSIVEDIRECTUV = 0;
  43288. _this.REFLECTIVITY = false;
  43289. _this.REFLECTIVITYDIRECTUV = 0;
  43290. _this.SPECULARTERM = false;
  43291. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43292. _this.MICROSURFACEAUTOMATIC = false;
  43293. _this.LODBASEDMICROSFURACE = false;
  43294. _this.MICROSURFACEMAP = false;
  43295. _this.MICROSURFACEMAPDIRECTUV = 0;
  43296. _this.METALLICWORKFLOW = false;
  43297. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43298. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43299. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43300. _this.AOSTOREINMETALMAPRED = false;
  43301. _this.ENVIRONMENTBRDF = false;
  43302. _this.NORMAL = false;
  43303. _this.TANGENT = false;
  43304. _this.BUMP = false;
  43305. _this.BUMPDIRECTUV = 0;
  43306. _this.OBJECTSPACE_NORMALMAP = false;
  43307. _this.PARALLAX = false;
  43308. _this.PARALLAXOCCLUSION = false;
  43309. _this.NORMALXYSCALE = true;
  43310. _this.LIGHTMAP = false;
  43311. _this.LIGHTMAPDIRECTUV = 0;
  43312. _this.USELIGHTMAPASSHADOWMAP = false;
  43313. _this.GAMMALIGHTMAP = false;
  43314. _this.REFLECTION = false;
  43315. _this.REFLECTIONMAP_3D = false;
  43316. _this.REFLECTIONMAP_SPHERICAL = false;
  43317. _this.REFLECTIONMAP_PLANAR = false;
  43318. _this.REFLECTIONMAP_CUBIC = false;
  43319. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43320. _this.REFLECTIONMAP_PROJECTION = false;
  43321. _this.REFLECTIONMAP_SKYBOX = false;
  43322. _this.REFLECTIONMAP_EXPLICIT = false;
  43323. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43324. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43325. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43326. _this.INVERTCUBICMAP = false;
  43327. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43328. _this.USESPHERICALINVERTEX = false;
  43329. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43330. _this.LODINREFLECTIONALPHA = false;
  43331. _this.GAMMAREFLECTION = false;
  43332. _this.RGBDREFLECTION = false;
  43333. _this.RADIANCEOCCLUSION = false;
  43334. _this.HORIZONOCCLUSION = false;
  43335. _this.REFRACTION = false;
  43336. _this.REFRACTIONMAP_3D = false;
  43337. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43338. _this.LODINREFRACTIONALPHA = false;
  43339. _this.GAMMAREFRACTION = false;
  43340. _this.RGBDREFRACTION = false;
  43341. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43342. _this.INSTANCES = false;
  43343. _this.NUM_BONE_INFLUENCERS = 0;
  43344. _this.BonesPerMesh = 0;
  43345. _this.NONUNIFORMSCALING = false;
  43346. _this.MORPHTARGETS = false;
  43347. _this.MORPHTARGETS_NORMAL = false;
  43348. _this.MORPHTARGETS_TANGENT = false;
  43349. _this.NUM_MORPH_INFLUENCERS = 0;
  43350. _this.IMAGEPROCESSING = false;
  43351. _this.VIGNETTE = false;
  43352. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43353. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43354. _this.TONEMAPPING = false;
  43355. _this.CONTRAST = false;
  43356. _this.COLORCURVES = false;
  43357. _this.COLORGRADING = false;
  43358. _this.COLORGRADING3D = false;
  43359. _this.SAMPLER3DGREENDEPTH = false;
  43360. _this.SAMPLER3DBGRMAP = false;
  43361. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43362. _this.EXPOSURE = false;
  43363. _this.USEPHYSICALLIGHTFALLOFF = false;
  43364. _this.TWOSIDEDLIGHTING = false;
  43365. _this.SHADOWFLOAT = false;
  43366. _this.CLIPPLANE = false;
  43367. _this.POINTSIZE = false;
  43368. _this.FOG = false;
  43369. _this.LOGARITHMICDEPTH = false;
  43370. _this.FORCENORMALFORWARD = false;
  43371. _this.SPECULARAA = false;
  43372. _this.UNLIT = false;
  43373. _this.rebuild();
  43374. return _this;
  43375. }
  43376. /**
  43377. * Resets the PBR Material defines.
  43378. */
  43379. PBRMaterialDefines.prototype.reset = function () {
  43380. _super.prototype.reset.call(this);
  43381. this.ALPHATESTVALUE = "0.5";
  43382. this.PBR = true;
  43383. };
  43384. return PBRMaterialDefines;
  43385. }(BABYLON.MaterialDefines));
  43386. /**
  43387. * The Physically based material base class of BJS.
  43388. *
  43389. * This offers the main features of a standard PBR material.
  43390. * For more information, please refer to the documentation :
  43391. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43392. */
  43393. var PBRBaseMaterial = /** @class */ (function (_super) {
  43394. __extends(PBRBaseMaterial, _super);
  43395. /**
  43396. * Instantiates a new PBRMaterial instance.
  43397. *
  43398. * @param name The material name
  43399. * @param scene The scene the material will be use in.
  43400. */
  43401. function PBRBaseMaterial(name, scene) {
  43402. var _this = _super.call(this, name, scene) || this;
  43403. /**
  43404. * Intensity of the direct lights e.g. the four lights available in your scene.
  43405. * This impacts both the direct diffuse and specular highlights.
  43406. */
  43407. _this._directIntensity = 1.0;
  43408. /**
  43409. * Intensity of the emissive part of the material.
  43410. * This helps controlling the emissive effect without modifying the emissive color.
  43411. */
  43412. _this._emissiveIntensity = 1.0;
  43413. /**
  43414. * Intensity of the environment e.g. how much the environment will light the object
  43415. * either through harmonics for rough material or through the refelction for shiny ones.
  43416. */
  43417. _this._environmentIntensity = 1.0;
  43418. /**
  43419. * This is a special control allowing the reduction of the specular highlights coming from the
  43420. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43421. */
  43422. _this._specularIntensity = 1.0;
  43423. /**
  43424. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43425. */
  43426. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43427. /**
  43428. * Debug Control allowing disabling the bump map on this material.
  43429. */
  43430. _this._disableBumpMap = false;
  43431. /**
  43432. * AKA Occlusion Texture Intensity in other nomenclature.
  43433. */
  43434. _this._ambientTextureStrength = 1.0;
  43435. /**
  43436. * The color of a material in ambient lighting.
  43437. */
  43438. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43439. /**
  43440. * AKA Diffuse Color in other nomenclature.
  43441. */
  43442. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43443. /**
  43444. * AKA Specular Color in other nomenclature.
  43445. */
  43446. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43447. /**
  43448. * The color applied when light is reflected from a material.
  43449. */
  43450. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43451. /**
  43452. * The color applied when light is emitted from a material.
  43453. */
  43454. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43455. /**
  43456. * AKA Glossiness in other nomenclature.
  43457. */
  43458. _this._microSurface = 0.9;
  43459. /**
  43460. * source material index of refraction (IOR)' / 'destination material IOR.
  43461. */
  43462. _this._indexOfRefraction = 0.66;
  43463. /**
  43464. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43465. */
  43466. _this._invertRefractionY = false;
  43467. /**
  43468. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43469. * Materials half opaque for instance using refraction could benefit from this control.
  43470. */
  43471. _this._linkRefractionWithTransparency = false;
  43472. /**
  43473. * Specifies that the material will use the light map as a show map.
  43474. */
  43475. _this._useLightmapAsShadowmap = false;
  43476. /**
  43477. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43478. * makes the reflect vector face the model (under horizon).
  43479. */
  43480. _this._useHorizonOcclusion = true;
  43481. /**
  43482. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43483. * too much the area relying on ambient texture to define their ambient occlusion.
  43484. */
  43485. _this._useRadianceOcclusion = true;
  43486. /**
  43487. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43488. */
  43489. _this._useAlphaFromAlbedoTexture = false;
  43490. /**
  43491. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43492. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43493. */
  43494. _this._useSpecularOverAlpha = true;
  43495. /**
  43496. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43497. */
  43498. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43499. /**
  43500. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43501. */
  43502. _this._useRoughnessFromMetallicTextureAlpha = true;
  43503. /**
  43504. * Specifies if the metallic texture contains the roughness information in its green channel.
  43505. */
  43506. _this._useRoughnessFromMetallicTextureGreen = false;
  43507. /**
  43508. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43509. */
  43510. _this._useMetallnessFromMetallicTextureBlue = false;
  43511. /**
  43512. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43513. */
  43514. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43515. /**
  43516. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43517. */
  43518. _this._useAmbientInGrayScale = false;
  43519. /**
  43520. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43521. * The material will try to infer what glossiness each pixel should be.
  43522. */
  43523. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43524. /**
  43525. * BJS is using an harcoded light falloff based on a manually sets up range.
  43526. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43527. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43528. */
  43529. _this._usePhysicalLightFalloff = true;
  43530. /**
  43531. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43532. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43533. */
  43534. _this._useRadianceOverAlpha = true;
  43535. /**
  43536. * Allows using an object space normal map (instead of tangent space).
  43537. */
  43538. _this._useObjectSpaceNormalMap = false;
  43539. /**
  43540. * Allows using the bump map in parallax mode.
  43541. */
  43542. _this._useParallax = false;
  43543. /**
  43544. * Allows using the bump map in parallax occlusion mode.
  43545. */
  43546. _this._useParallaxOcclusion = false;
  43547. /**
  43548. * Controls the scale bias of the parallax mode.
  43549. */
  43550. _this._parallaxScaleBias = 0.05;
  43551. /**
  43552. * If sets to true, disables all the lights affecting the material.
  43553. */
  43554. _this._disableLighting = false;
  43555. /**
  43556. * Number of Simultaneous lights allowed on the material.
  43557. */
  43558. _this._maxSimultaneousLights = 4;
  43559. /**
  43560. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43561. */
  43562. _this._invertNormalMapX = false;
  43563. /**
  43564. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43565. */
  43566. _this._invertNormalMapY = false;
  43567. /**
  43568. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43569. */
  43570. _this._twoSidedLighting = false;
  43571. /**
  43572. * Defines the alpha limits in alpha test mode.
  43573. */
  43574. _this._alphaCutOff = 0.4;
  43575. /**
  43576. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43577. */
  43578. _this._forceAlphaTest = false;
  43579. /**
  43580. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43581. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43582. */
  43583. _this._useAlphaFresnel = false;
  43584. /**
  43585. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43586. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43587. */
  43588. _this._useLinearAlphaFresnel = false;
  43589. /**
  43590. * The transparency mode of the material.
  43591. */
  43592. _this._transparencyMode = null;
  43593. /**
  43594. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43595. * from cos thetav and roughness:
  43596. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43597. */
  43598. _this._environmentBRDFTexture = null;
  43599. /**
  43600. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43601. */
  43602. _this._forceIrradianceInFragment = false;
  43603. /**
  43604. * Force normal to face away from face.
  43605. */
  43606. _this._forceNormalForward = false;
  43607. /**
  43608. * Enables specular anti aliasing in the PBR shader.
  43609. * It will both interacts on the Geometry for analytical and IBL lighting.
  43610. * It also prefilter the roughness map based on the bump values.
  43611. */
  43612. _this._enableSpecularAntiAliasing = false;
  43613. /**
  43614. * Stores the available render targets.
  43615. */
  43616. _this._renderTargets = new BABYLON.SmartArray(16);
  43617. /**
  43618. * Sets the global ambient color for the material used in lighting calculations.
  43619. */
  43620. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43621. /**
  43622. * If set to true, no lighting calculations will be applied.
  43623. */
  43624. _this._unlit = false;
  43625. // Setup the default processing configuration to the scene.
  43626. _this._attachImageProcessingConfiguration(null);
  43627. _this.getRenderTargetTextures = function () {
  43628. _this._renderTargets.reset();
  43629. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43630. _this._renderTargets.push(_this._reflectionTexture);
  43631. }
  43632. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43633. _this._renderTargets.push(_this._refractionTexture);
  43634. }
  43635. return _this._renderTargets;
  43636. };
  43637. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43638. return _this;
  43639. }
  43640. /**
  43641. * Attaches a new image processing configuration to the PBR Material.
  43642. * @param configuration
  43643. */
  43644. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43645. var _this = this;
  43646. if (configuration === this._imageProcessingConfiguration) {
  43647. return;
  43648. }
  43649. // Detaches observer.
  43650. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43651. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43652. }
  43653. // Pick the scene configuration if needed.
  43654. if (!configuration) {
  43655. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43656. }
  43657. else {
  43658. this._imageProcessingConfiguration = configuration;
  43659. }
  43660. // Attaches observer.
  43661. if (this._imageProcessingConfiguration) {
  43662. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43663. _this._markAllSubMeshesAsImageProcessingDirty();
  43664. });
  43665. }
  43666. };
  43667. /**
  43668. * Gets the name of the material class.
  43669. */
  43670. PBRBaseMaterial.prototype.getClassName = function () {
  43671. return "PBRBaseMaterial";
  43672. };
  43673. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43674. /**
  43675. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43676. */
  43677. get: function () {
  43678. return this._useLogarithmicDepth;
  43679. },
  43680. /**
  43681. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43682. */
  43683. set: function (value) {
  43684. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43685. },
  43686. enumerable: true,
  43687. configurable: true
  43688. });
  43689. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43690. /**
  43691. * Gets the current transparency mode.
  43692. */
  43693. get: function () {
  43694. return this._transparencyMode;
  43695. },
  43696. /**
  43697. * Sets the transparency mode of the material.
  43698. *
  43699. * | Value | Type | Description |
  43700. * | ----- | ----------------------------------- | ----------- |
  43701. * | 0 | OPAQUE | |
  43702. * | 1 | ALPHATEST | |
  43703. * | 2 | ALPHABLEND | |
  43704. * | 3 | ALPHATESTANDBLEND | |
  43705. *
  43706. */
  43707. set: function (value) {
  43708. if (this._transparencyMode === value) {
  43709. return;
  43710. }
  43711. this._transparencyMode = value;
  43712. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43713. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43714. },
  43715. enumerable: true,
  43716. configurable: true
  43717. });
  43718. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43719. /**
  43720. * Returns true if alpha blending should be disabled.
  43721. */
  43722. get: function () {
  43723. return (this._linkRefractionWithTransparency ||
  43724. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43725. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43726. },
  43727. enumerable: true,
  43728. configurable: true
  43729. });
  43730. /**
  43731. * Specifies whether or not this material should be rendered in alpha blend mode.
  43732. */
  43733. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43734. if (this._disableAlphaBlending) {
  43735. return false;
  43736. }
  43737. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43738. };
  43739. /**
  43740. * Specifies if the mesh will require alpha blending.
  43741. * @param mesh - BJS mesh.
  43742. */
  43743. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43744. if (this._disableAlphaBlending) {
  43745. return false;
  43746. }
  43747. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43748. };
  43749. /**
  43750. * Specifies whether or not this material should be rendered in alpha test mode.
  43751. */
  43752. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43753. if (this._forceAlphaTest) {
  43754. return true;
  43755. }
  43756. if (this._linkRefractionWithTransparency) {
  43757. return false;
  43758. }
  43759. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43760. };
  43761. /**
  43762. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43763. */
  43764. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43765. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43766. };
  43767. /**
  43768. * Gets the texture used for the alpha test.
  43769. */
  43770. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43771. return this._albedoTexture;
  43772. };
  43773. /**
  43774. * Specifies that the submesh is ready to be used.
  43775. * @param mesh - BJS mesh.
  43776. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43777. * @param useInstances - Specifies that instances should be used.
  43778. * @returns - boolean indicating that the submesh is ready or not.
  43779. */
  43780. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43781. if (subMesh.effect && this.isFrozen) {
  43782. if (this._wasPreviouslyReady) {
  43783. return true;
  43784. }
  43785. }
  43786. if (!subMesh._materialDefines) {
  43787. subMesh._materialDefines = new PBRMaterialDefines();
  43788. }
  43789. var defines = subMesh._materialDefines;
  43790. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43791. if (defines._renderId === this.getScene().getRenderId()) {
  43792. return true;
  43793. }
  43794. }
  43795. var scene = this.getScene();
  43796. var engine = scene.getEngine();
  43797. if (defines._areTexturesDirty) {
  43798. if (scene.texturesEnabled) {
  43799. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43800. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43801. return false;
  43802. }
  43803. }
  43804. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43805. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43806. return false;
  43807. }
  43808. }
  43809. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43810. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43811. return false;
  43812. }
  43813. }
  43814. var reflectionTexture = this._getReflectionTexture();
  43815. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43816. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43817. return false;
  43818. }
  43819. }
  43820. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43821. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43822. return false;
  43823. }
  43824. }
  43825. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43826. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43827. return false;
  43828. }
  43829. }
  43830. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43831. if (this._metallicTexture) {
  43832. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43833. return false;
  43834. }
  43835. }
  43836. else if (this._reflectivityTexture) {
  43837. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43838. return false;
  43839. }
  43840. }
  43841. if (this._microSurfaceTexture) {
  43842. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43843. return false;
  43844. }
  43845. }
  43846. }
  43847. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43848. // Bump texture cannot be not blocking.
  43849. if (!this._bumpTexture.isReady()) {
  43850. return false;
  43851. }
  43852. }
  43853. var refractionTexture = this._getRefractionTexture();
  43854. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43855. if (!refractionTexture.isReadyOrNotBlocking()) {
  43856. return false;
  43857. }
  43858. }
  43859. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43860. // This is blocking.
  43861. if (!this._environmentBRDFTexture.isReady()) {
  43862. return false;
  43863. }
  43864. }
  43865. }
  43866. }
  43867. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43868. if (!this._imageProcessingConfiguration.isReady()) {
  43869. return false;
  43870. }
  43871. }
  43872. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43873. mesh.createNormals(true);
  43874. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43875. }
  43876. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43877. if (effect) {
  43878. scene.resetCachedMaterial();
  43879. subMesh.setEffect(effect, defines);
  43880. this.buildUniformLayout();
  43881. }
  43882. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43883. return false;
  43884. }
  43885. defines._renderId = scene.getRenderId();
  43886. this._wasPreviouslyReady = true;
  43887. return true;
  43888. };
  43889. /**
  43890. * Specifies if the material uses metallic roughness workflow.
  43891. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43892. */
  43893. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43894. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43895. return true;
  43896. }
  43897. return false;
  43898. };
  43899. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43900. if (onCompiled === void 0) { onCompiled = null; }
  43901. if (onError === void 0) { onError = null; }
  43902. if (useInstances === void 0) { useInstances = null; }
  43903. if (useClipPlane === void 0) { useClipPlane = null; }
  43904. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43905. if (!defines.isDirty) {
  43906. return null;
  43907. }
  43908. defines.markAsProcessed();
  43909. var scene = this.getScene();
  43910. var engine = scene.getEngine();
  43911. // Fallbacks
  43912. var fallbacks = new BABYLON.EffectFallbacks();
  43913. var fallbackRank = 0;
  43914. if (defines.USESPHERICALINVERTEX) {
  43915. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43916. }
  43917. if (defines.FOG) {
  43918. fallbacks.addFallback(fallbackRank, "FOG");
  43919. }
  43920. if (defines.SPECULARAA) {
  43921. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43922. }
  43923. if (defines.POINTSIZE) {
  43924. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43925. }
  43926. if (defines.LOGARITHMICDEPTH) {
  43927. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43928. }
  43929. if (defines.PARALLAX) {
  43930. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43931. }
  43932. if (defines.PARALLAXOCCLUSION) {
  43933. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43934. }
  43935. if (defines.ENVIRONMENTBRDF) {
  43936. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43937. }
  43938. if (defines.TANGENT) {
  43939. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43940. }
  43941. if (defines.BUMP) {
  43942. fallbacks.addFallback(fallbackRank++, "BUMP");
  43943. }
  43944. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43945. if (defines.SPECULARTERM) {
  43946. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43947. }
  43948. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43949. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43950. }
  43951. if (defines.LIGHTMAP) {
  43952. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43953. }
  43954. if (defines.NORMAL) {
  43955. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43956. }
  43957. if (defines.AMBIENT) {
  43958. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43959. }
  43960. if (defines.EMISSIVE) {
  43961. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43962. }
  43963. if (defines.VERTEXCOLOR) {
  43964. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43965. }
  43966. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43967. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43968. }
  43969. if (defines.MORPHTARGETS) {
  43970. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43971. }
  43972. //Attributes
  43973. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43974. if (defines.NORMAL) {
  43975. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43976. }
  43977. if (defines.TANGENT) {
  43978. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43979. }
  43980. if (defines.UV1) {
  43981. attribs.push(BABYLON.VertexBuffer.UVKind);
  43982. }
  43983. if (defines.UV2) {
  43984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43985. }
  43986. if (defines.VERTEXCOLOR) {
  43987. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43988. }
  43989. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43990. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43991. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43992. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43993. "vFogInfos", "vFogColor", "pointSize",
  43994. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43995. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43996. "mBones",
  43997. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43998. "vLightingIntensity",
  43999. "logarithmicDepthConstant",
  44000. "vSphericalX", "vSphericalY", "vSphericalZ",
  44001. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44002. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44003. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44004. "vTangentSpaceParams"
  44005. ];
  44006. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44007. "bumpSampler", "lightmapSampler", "opacitySampler",
  44008. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44009. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44010. "microSurfaceSampler", "environmentBrdfSampler"];
  44011. var uniformBuffers = ["Material", "Scene"];
  44012. if (BABYLON.ImageProcessingConfiguration) {
  44013. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44014. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44015. }
  44016. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44017. uniformsNames: uniforms,
  44018. uniformBuffersNames: uniformBuffers,
  44019. samplers: samplers,
  44020. defines: defines,
  44021. maxSimultaneousLights: this._maxSimultaneousLights
  44022. });
  44023. var join = defines.toString();
  44024. return engine.createEffect("pbr", {
  44025. attributes: attribs,
  44026. uniformsNames: uniforms,
  44027. uniformBuffersNames: uniformBuffers,
  44028. samplers: samplers,
  44029. defines: join,
  44030. fallbacks: fallbacks,
  44031. onCompiled: onCompiled,
  44032. onError: onError,
  44033. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44034. }, engine);
  44035. };
  44036. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44037. if (useInstances === void 0) { useInstances = null; }
  44038. if (useClipPlane === void 0) { useClipPlane = null; }
  44039. var scene = this.getScene();
  44040. var engine = scene.getEngine();
  44041. // Lights
  44042. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44043. defines._needNormals = true;
  44044. // Textures
  44045. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44046. if (defines._areTexturesDirty) {
  44047. defines._needUVs = false;
  44048. if (scene.texturesEnabled) {
  44049. if (scene.getEngine().getCaps().textureLOD) {
  44050. defines.LODBASEDMICROSFURACE = true;
  44051. }
  44052. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44053. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44054. }
  44055. else {
  44056. defines.ALBEDO = false;
  44057. }
  44058. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44059. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44060. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44061. }
  44062. else {
  44063. defines.AMBIENT = false;
  44064. }
  44065. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44066. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44067. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44068. }
  44069. else {
  44070. defines.OPACITY = false;
  44071. }
  44072. var reflectionTexture = this._getReflectionTexture();
  44073. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44074. defines.REFLECTION = true;
  44075. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44076. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44077. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44078. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44079. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44080. defines.INVERTCUBICMAP = true;
  44081. }
  44082. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44083. switch (reflectionTexture.coordinatesMode) {
  44084. case BABYLON.Texture.EXPLICIT_MODE:
  44085. defines.REFLECTIONMAP_EXPLICIT = true;
  44086. break;
  44087. case BABYLON.Texture.PLANAR_MODE:
  44088. defines.REFLECTIONMAP_PLANAR = true;
  44089. break;
  44090. case BABYLON.Texture.PROJECTION_MODE:
  44091. defines.REFLECTIONMAP_PROJECTION = true;
  44092. break;
  44093. case BABYLON.Texture.SKYBOX_MODE:
  44094. defines.REFLECTIONMAP_SKYBOX = true;
  44095. break;
  44096. case BABYLON.Texture.SPHERICAL_MODE:
  44097. defines.REFLECTIONMAP_SPHERICAL = true;
  44098. break;
  44099. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44100. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44101. break;
  44102. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44103. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44104. break;
  44105. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44106. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44107. break;
  44108. case BABYLON.Texture.CUBIC_MODE:
  44109. case BABYLON.Texture.INVCUBIC_MODE:
  44110. default:
  44111. defines.REFLECTIONMAP_CUBIC = true;
  44112. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44113. break;
  44114. }
  44115. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44116. if (reflectionTexture.sphericalPolynomial) {
  44117. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44118. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44119. defines.USESPHERICALINVERTEX = false;
  44120. }
  44121. else {
  44122. defines.USESPHERICALINVERTEX = true;
  44123. }
  44124. }
  44125. }
  44126. }
  44127. else {
  44128. defines.REFLECTION = false;
  44129. defines.REFLECTIONMAP_3D = false;
  44130. defines.REFLECTIONMAP_SPHERICAL = false;
  44131. defines.REFLECTIONMAP_PLANAR = false;
  44132. defines.REFLECTIONMAP_CUBIC = false;
  44133. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44134. defines.REFLECTIONMAP_PROJECTION = false;
  44135. defines.REFLECTIONMAP_SKYBOX = false;
  44136. defines.REFLECTIONMAP_EXPLICIT = false;
  44137. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44138. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44139. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44140. defines.INVERTCUBICMAP = false;
  44141. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44142. defines.USESPHERICALINVERTEX = false;
  44143. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44144. defines.LODINREFLECTIONALPHA = false;
  44145. defines.GAMMAREFLECTION = false;
  44146. defines.RGBDREFLECTION = false;
  44147. }
  44148. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44149. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44150. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44151. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44152. }
  44153. else {
  44154. defines.LIGHTMAP = false;
  44155. }
  44156. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44157. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44158. }
  44159. else {
  44160. defines.EMISSIVE = false;
  44161. }
  44162. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44163. if (this._metallicTexture) {
  44164. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44165. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44166. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44167. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44168. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44169. }
  44170. else if (this._reflectivityTexture) {
  44171. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44172. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44173. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44174. }
  44175. else {
  44176. defines.REFLECTIVITY = false;
  44177. }
  44178. if (this._microSurfaceTexture) {
  44179. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44180. }
  44181. else {
  44182. defines.MICROSURFACEMAP = false;
  44183. }
  44184. }
  44185. else {
  44186. defines.REFLECTIVITY = false;
  44187. defines.MICROSURFACEMAP = false;
  44188. }
  44189. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44190. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44191. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44192. defines.PARALLAX = true;
  44193. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44194. }
  44195. else {
  44196. defines.PARALLAX = false;
  44197. }
  44198. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44199. }
  44200. else {
  44201. defines.BUMP = false;
  44202. }
  44203. var refractionTexture = this._getRefractionTexture();
  44204. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44205. defines.REFRACTION = true;
  44206. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44207. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44208. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44209. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44210. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44211. if (this._linkRefractionWithTransparency) {
  44212. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44213. }
  44214. }
  44215. else {
  44216. defines.REFRACTION = false;
  44217. }
  44218. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44219. defines.ENVIRONMENTBRDF = true;
  44220. }
  44221. else {
  44222. defines.ENVIRONMENTBRDF = false;
  44223. }
  44224. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44225. defines.ALPHAFROMALBEDO = true;
  44226. }
  44227. else {
  44228. defines.ALPHAFROMALBEDO = false;
  44229. }
  44230. }
  44231. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44232. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44233. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44234. if (!this.backFaceCulling && this._twoSidedLighting) {
  44235. defines.TWOSIDEDLIGHTING = true;
  44236. }
  44237. else {
  44238. defines.TWOSIDEDLIGHTING = false;
  44239. }
  44240. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44241. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44242. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44243. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44244. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44245. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44246. }
  44247. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44248. this._imageProcessingConfiguration.prepareDefines(defines);
  44249. }
  44250. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44251. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44252. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44253. // Misc.
  44254. if (defines._areMiscDirty) {
  44255. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44256. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44257. }
  44258. // Values that need to be evaluated on every frame
  44259. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44260. // Attribs
  44261. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44262. };
  44263. /**
  44264. * Force shader compilation
  44265. */
  44266. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44267. var _this = this;
  44268. var localOptions = __assign({ clipPlane: false }, options);
  44269. var defines = new PBRMaterialDefines();
  44270. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44271. if (effect.isReady()) {
  44272. if (onCompiled) {
  44273. onCompiled(this);
  44274. }
  44275. }
  44276. else {
  44277. effect.onCompileObservable.add(function () {
  44278. if (onCompiled) {
  44279. onCompiled(_this);
  44280. }
  44281. });
  44282. }
  44283. };
  44284. /**
  44285. * Initializes the uniform buffer layout for the shader.
  44286. */
  44287. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44288. // Order is important !
  44289. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44290. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44291. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44292. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44293. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44294. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44295. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44296. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44297. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44298. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44299. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44300. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44301. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44302. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44303. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44304. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44305. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44306. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44307. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44308. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44309. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44310. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44311. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44312. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44313. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44314. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44315. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44316. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44317. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44318. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44319. this._uniformBuffer.addUniform("pointSize", 1);
  44320. this._uniformBuffer.create();
  44321. };
  44322. /**
  44323. * Unbinds the textures.
  44324. */
  44325. PBRBaseMaterial.prototype.unbind = function () {
  44326. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44327. this._uniformBuffer.setTexture("reflectionSampler", null);
  44328. }
  44329. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44330. this._uniformBuffer.setTexture("refractionSampler", null);
  44331. }
  44332. _super.prototype.unbind.call(this);
  44333. };
  44334. /**
  44335. * Binds the submesh data.
  44336. * @param world - The world matrix.
  44337. * @param mesh - The BJS mesh.
  44338. * @param subMesh - A submesh of the BJS mesh.
  44339. */
  44340. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44341. var scene = this.getScene();
  44342. var defines = subMesh._materialDefines;
  44343. if (!defines) {
  44344. return;
  44345. }
  44346. var effect = subMesh.effect;
  44347. if (!effect) {
  44348. return;
  44349. }
  44350. this._activeEffect = effect;
  44351. // Matrices
  44352. this.bindOnlyWorldMatrix(world);
  44353. // Normal Matrix
  44354. if (defines.OBJECTSPACE_NORMALMAP) {
  44355. world.toNormalMatrix(this._normalMatrix);
  44356. this.bindOnlyNormalMatrix(this._normalMatrix);
  44357. }
  44358. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44359. // Bones
  44360. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44361. var reflectionTexture = null;
  44362. if (mustRebind) {
  44363. this._uniformBuffer.bindToEffect(effect, "Material");
  44364. this.bindViewProjection(effect);
  44365. reflectionTexture = this._getReflectionTexture();
  44366. var refractionTexture = this._getRefractionTexture();
  44367. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44368. // Texture uniforms
  44369. if (scene.texturesEnabled) {
  44370. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44371. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44372. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44373. }
  44374. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44375. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44376. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44377. }
  44378. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44379. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44380. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44381. }
  44382. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44383. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44384. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44385. if (reflectionTexture.boundingBoxSize) {
  44386. var cubeTexture = reflectionTexture;
  44387. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44388. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44389. }
  44390. var polynomials = reflectionTexture.sphericalPolynomial;
  44391. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44392. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44393. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44394. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44395. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44396. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44397. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44398. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44399. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44400. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44401. }
  44402. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44403. }
  44404. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44405. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44406. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44407. }
  44408. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44409. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44410. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44411. }
  44412. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44413. if (this._metallicTexture) {
  44414. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44415. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44416. }
  44417. else if (this._reflectivityTexture) {
  44418. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44419. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44420. }
  44421. if (this._microSurfaceTexture) {
  44422. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44423. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44424. }
  44425. }
  44426. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44427. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44428. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44429. if (scene._mirroredCameraPosition) {
  44430. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44431. }
  44432. else {
  44433. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44434. }
  44435. }
  44436. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44437. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44438. var depth = 1.0;
  44439. if (!refractionTexture.isCube) {
  44440. if (refractionTexture.depth) {
  44441. depth = refractionTexture.depth;
  44442. }
  44443. }
  44444. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44445. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44446. }
  44447. }
  44448. // Point size
  44449. if (this.pointsCloud) {
  44450. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44451. }
  44452. // Colors
  44453. if (defines.METALLICWORKFLOW) {
  44454. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44455. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44456. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44457. }
  44458. else {
  44459. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44460. }
  44461. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44462. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44463. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44464. // Misc
  44465. this._lightingInfos.x = this._directIntensity;
  44466. this._lightingInfos.y = this._emissiveIntensity;
  44467. this._lightingInfos.z = this._environmentIntensity;
  44468. this._lightingInfos.w = this._specularIntensity;
  44469. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44470. }
  44471. // Textures
  44472. if (scene.texturesEnabled) {
  44473. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44474. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44475. }
  44476. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44477. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44478. }
  44479. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44480. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44481. }
  44482. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44483. if (defines.LODBASEDMICROSFURACE) {
  44484. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44485. }
  44486. else {
  44487. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44488. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44489. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44490. }
  44491. }
  44492. if (defines.ENVIRONMENTBRDF) {
  44493. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44494. }
  44495. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44496. if (defines.LODBASEDMICROSFURACE) {
  44497. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44498. }
  44499. else {
  44500. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44501. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44502. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44503. }
  44504. }
  44505. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44506. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44507. }
  44508. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44509. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44510. }
  44511. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44512. if (this._metallicTexture) {
  44513. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44514. }
  44515. else if (this._reflectivityTexture) {
  44516. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44517. }
  44518. if (this._microSurfaceTexture) {
  44519. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44520. }
  44521. }
  44522. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44523. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44524. }
  44525. }
  44526. // Clip plane
  44527. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44528. // Colors
  44529. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44530. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44531. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44532. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44533. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44534. }
  44535. if (mustRebind || !this.isFrozen) {
  44536. // Lights
  44537. if (scene.lightsEnabled && !this._disableLighting) {
  44538. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44539. }
  44540. // View
  44541. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44542. this.bindView(effect);
  44543. }
  44544. // Fog
  44545. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44546. // Morph targets
  44547. if (defines.NUM_MORPH_INFLUENCERS) {
  44548. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44549. }
  44550. // image processing
  44551. this._imageProcessingConfiguration.bind(this._activeEffect);
  44552. // Log. depth
  44553. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44554. }
  44555. this._uniformBuffer.update();
  44556. this._afterBind(mesh, this._activeEffect);
  44557. };
  44558. /**
  44559. * Returns the animatable textures.
  44560. * @returns - Array of animatable textures.
  44561. */
  44562. PBRBaseMaterial.prototype.getAnimatables = function () {
  44563. var results = [];
  44564. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44565. results.push(this._albedoTexture);
  44566. }
  44567. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44568. results.push(this._ambientTexture);
  44569. }
  44570. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44571. results.push(this._opacityTexture);
  44572. }
  44573. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44574. results.push(this._reflectionTexture);
  44575. }
  44576. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44577. results.push(this._emissiveTexture);
  44578. }
  44579. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44580. results.push(this._metallicTexture);
  44581. }
  44582. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44583. results.push(this._reflectivityTexture);
  44584. }
  44585. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44586. results.push(this._bumpTexture);
  44587. }
  44588. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44589. results.push(this._lightmapTexture);
  44590. }
  44591. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44592. results.push(this._refractionTexture);
  44593. }
  44594. return results;
  44595. };
  44596. /**
  44597. * Returns the texture used for reflections.
  44598. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44599. */
  44600. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44601. if (this._reflectionTexture) {
  44602. return this._reflectionTexture;
  44603. }
  44604. return this.getScene().environmentTexture;
  44605. };
  44606. /**
  44607. * Returns the texture used for refraction or null if none is used.
  44608. * @returns - Refection texture if present. If no refraction texture and refraction
  44609. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44610. */
  44611. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44612. if (this._refractionTexture) {
  44613. return this._refractionTexture;
  44614. }
  44615. if (this._linkRefractionWithTransparency) {
  44616. return this.getScene().environmentTexture;
  44617. }
  44618. return null;
  44619. };
  44620. /**
  44621. * Disposes the resources of the material.
  44622. * @param forceDisposeEffect - Forces the disposal of effects.
  44623. * @param forceDisposeTextures - Forces the disposal of all textures.
  44624. */
  44625. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44626. if (forceDisposeTextures) {
  44627. if (this._albedoTexture) {
  44628. this._albedoTexture.dispose();
  44629. }
  44630. if (this._ambientTexture) {
  44631. this._ambientTexture.dispose();
  44632. }
  44633. if (this._opacityTexture) {
  44634. this._opacityTexture.dispose();
  44635. }
  44636. if (this._reflectionTexture) {
  44637. this._reflectionTexture.dispose();
  44638. }
  44639. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44640. this._environmentBRDFTexture.dispose();
  44641. }
  44642. if (this._emissiveTexture) {
  44643. this._emissiveTexture.dispose();
  44644. }
  44645. if (this._metallicTexture) {
  44646. this._metallicTexture.dispose();
  44647. }
  44648. if (this._reflectivityTexture) {
  44649. this._reflectivityTexture.dispose();
  44650. }
  44651. if (this._bumpTexture) {
  44652. this._bumpTexture.dispose();
  44653. }
  44654. if (this._lightmapTexture) {
  44655. this._lightmapTexture.dispose();
  44656. }
  44657. if (this._refractionTexture) {
  44658. this._refractionTexture.dispose();
  44659. }
  44660. }
  44661. this._renderTargets.dispose();
  44662. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44663. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44664. }
  44665. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44666. };
  44667. /**
  44668. * Stores the reflectivity values based on metallic roughness workflow.
  44669. */
  44670. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44671. __decorate([
  44672. BABYLON.serializeAsImageProcessingConfiguration()
  44673. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44674. __decorate([
  44675. BABYLON.serialize()
  44676. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44677. __decorate([
  44678. BABYLON.serialize()
  44679. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44680. return PBRBaseMaterial;
  44681. }(BABYLON.PushMaterial));
  44682. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44683. })(BABYLON || (BABYLON = {}));
  44684. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44685. var BABYLON;
  44686. (function (BABYLON) {
  44687. /**
  44688. * The Physically based simple base material of BJS.
  44689. *
  44690. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44691. * It is used as the base class for both the specGloss and metalRough conventions.
  44692. */
  44693. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44694. __extends(PBRBaseSimpleMaterial, _super);
  44695. /**
  44696. * Instantiates a new PBRMaterial instance.
  44697. *
  44698. * @param name The material name
  44699. * @param scene The scene the material will be use in.
  44700. */
  44701. function PBRBaseSimpleMaterial(name, scene) {
  44702. var _this = _super.call(this, name, scene) || this;
  44703. /**
  44704. * Number of Simultaneous lights allowed on the material.
  44705. */
  44706. _this.maxSimultaneousLights = 4;
  44707. /**
  44708. * If sets to true, disables all the lights affecting the material.
  44709. */
  44710. _this.disableLighting = false;
  44711. /**
  44712. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44713. */
  44714. _this.invertNormalMapX = false;
  44715. /**
  44716. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44717. */
  44718. _this.invertNormalMapY = false;
  44719. /**
  44720. * Emissivie color used to self-illuminate the model.
  44721. */
  44722. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44723. /**
  44724. * Occlusion Channel Strenght.
  44725. */
  44726. _this.occlusionStrength = 1.0;
  44727. _this.useLightmapAsShadowmap = false;
  44728. _this._useAlphaFromAlbedoTexture = true;
  44729. _this._useAmbientInGrayScale = true;
  44730. return _this;
  44731. }
  44732. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44733. /**
  44734. * Gets the current double sided mode.
  44735. */
  44736. get: function () {
  44737. return this._twoSidedLighting;
  44738. },
  44739. /**
  44740. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44741. */
  44742. set: function (value) {
  44743. if (this._twoSidedLighting === value) {
  44744. return;
  44745. }
  44746. this._twoSidedLighting = value;
  44747. this.backFaceCulling = !value;
  44748. this._markAllSubMeshesAsTexturesDirty();
  44749. },
  44750. enumerable: true,
  44751. configurable: true
  44752. });
  44753. /**
  44754. * Return the active textures of the material.
  44755. */
  44756. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44757. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44758. if (this.environmentTexture) {
  44759. activeTextures.push(this.environmentTexture);
  44760. }
  44761. if (this.normalTexture) {
  44762. activeTextures.push(this.normalTexture);
  44763. }
  44764. if (this.emissiveTexture) {
  44765. activeTextures.push(this.emissiveTexture);
  44766. }
  44767. if (this.occlusionTexture) {
  44768. activeTextures.push(this.occlusionTexture);
  44769. }
  44770. if (this.lightmapTexture) {
  44771. activeTextures.push(this.lightmapTexture);
  44772. }
  44773. return activeTextures;
  44774. };
  44775. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44776. if (_super.prototype.hasTexture.call(this, texture)) {
  44777. return true;
  44778. }
  44779. if (this.lightmapTexture === texture) {
  44780. return true;
  44781. }
  44782. return false;
  44783. };
  44784. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44785. return "PBRBaseSimpleMaterial";
  44786. };
  44787. __decorate([
  44788. BABYLON.serialize(),
  44789. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44790. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44791. __decorate([
  44792. BABYLON.serialize(),
  44793. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44794. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44795. __decorate([
  44796. BABYLON.serializeAsTexture(),
  44797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44798. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44799. __decorate([
  44800. BABYLON.serialize(),
  44801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44802. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44803. __decorate([
  44804. BABYLON.serialize(),
  44805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44806. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44807. __decorate([
  44808. BABYLON.serializeAsTexture(),
  44809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44810. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44811. __decorate([
  44812. BABYLON.serializeAsColor3("emissive"),
  44813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44814. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44815. __decorate([
  44816. BABYLON.serializeAsTexture(),
  44817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44818. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44819. __decorate([
  44820. BABYLON.serialize(),
  44821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44822. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44823. __decorate([
  44824. BABYLON.serializeAsTexture(),
  44825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44826. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44827. __decorate([
  44828. BABYLON.serialize(),
  44829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44830. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44831. __decorate([
  44832. BABYLON.serialize()
  44833. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44834. __decorate([
  44835. BABYLON.serializeAsTexture(),
  44836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44837. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44838. __decorate([
  44839. BABYLON.serialize(),
  44840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44841. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44842. return PBRBaseSimpleMaterial;
  44843. }(BABYLON.PBRBaseMaterial));
  44844. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44845. })(BABYLON || (BABYLON = {}));
  44846. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44847. var BABYLON;
  44848. (function (BABYLON) {
  44849. /**
  44850. * The Physically based material of BJS.
  44851. *
  44852. * This offers the main features of a standard PBR material.
  44853. * For more information, please refer to the documentation :
  44854. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44855. */
  44856. var PBRMaterial = /** @class */ (function (_super) {
  44857. __extends(PBRMaterial, _super);
  44858. /**
  44859. * Instantiates a new PBRMaterial instance.
  44860. *
  44861. * @param name The material name
  44862. * @param scene The scene the material will be use in.
  44863. */
  44864. function PBRMaterial(name, scene) {
  44865. var _this = _super.call(this, name, scene) || this;
  44866. /**
  44867. * Intensity of the direct lights e.g. the four lights available in your scene.
  44868. * This impacts both the direct diffuse and specular highlights.
  44869. */
  44870. _this.directIntensity = 1.0;
  44871. /**
  44872. * Intensity of the emissive part of the material.
  44873. * This helps controlling the emissive effect without modifying the emissive color.
  44874. */
  44875. _this.emissiveIntensity = 1.0;
  44876. /**
  44877. * Intensity of the environment e.g. how much the environment will light the object
  44878. * either through harmonics for rough material or through the refelction for shiny ones.
  44879. */
  44880. _this.environmentIntensity = 1.0;
  44881. /**
  44882. * This is a special control allowing the reduction of the specular highlights coming from the
  44883. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44884. */
  44885. _this.specularIntensity = 1.0;
  44886. /**
  44887. * Debug Control allowing disabling the bump map on this material.
  44888. */
  44889. _this.disableBumpMap = false;
  44890. /**
  44891. * AKA Occlusion Texture Intensity in other nomenclature.
  44892. */
  44893. _this.ambientTextureStrength = 1.0;
  44894. /**
  44895. * The color of a material in ambient lighting.
  44896. */
  44897. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44898. /**
  44899. * AKA Diffuse Color in other nomenclature.
  44900. */
  44901. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44902. /**
  44903. * AKA Specular Color in other nomenclature.
  44904. */
  44905. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44906. /**
  44907. * The color reflected from the material.
  44908. */
  44909. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44910. /**
  44911. * The color emitted from the material.
  44912. */
  44913. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44914. /**
  44915. * AKA Glossiness in other nomenclature.
  44916. */
  44917. _this.microSurface = 1.0;
  44918. /**
  44919. * source material index of refraction (IOR)' / 'destination material IOR.
  44920. */
  44921. _this.indexOfRefraction = 0.66;
  44922. /**
  44923. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44924. */
  44925. _this.invertRefractionY = false;
  44926. /**
  44927. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44928. * Materials half opaque for instance using refraction could benefit from this control.
  44929. */
  44930. _this.linkRefractionWithTransparency = false;
  44931. _this.useLightmapAsShadowmap = false;
  44932. /**
  44933. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44934. */
  44935. _this.useAlphaFromAlbedoTexture = false;
  44936. /**
  44937. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44938. */
  44939. _this.forceAlphaTest = false;
  44940. /**
  44941. * Defines the alpha limits in alpha test mode.
  44942. */
  44943. _this.alphaCutOff = 0.4;
  44944. /**
  44945. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44946. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44947. */
  44948. _this.useSpecularOverAlpha = true;
  44949. /**
  44950. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44951. */
  44952. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44953. /**
  44954. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44955. */
  44956. _this.useRoughnessFromMetallicTextureAlpha = true;
  44957. /**
  44958. * Specifies if the metallic texture contains the roughness information in its green channel.
  44959. */
  44960. _this.useRoughnessFromMetallicTextureGreen = false;
  44961. /**
  44962. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44963. */
  44964. _this.useMetallnessFromMetallicTextureBlue = false;
  44965. /**
  44966. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44967. */
  44968. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44969. /**
  44970. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44971. */
  44972. _this.useAmbientInGrayScale = false;
  44973. /**
  44974. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44975. * The material will try to infer what glossiness each pixel should be.
  44976. */
  44977. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44978. /**
  44979. * BJS is using an harcoded light falloff based on a manually sets up range.
  44980. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44981. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44982. */
  44983. _this.usePhysicalLightFalloff = true;
  44984. /**
  44985. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44986. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44987. */
  44988. _this.useRadianceOverAlpha = true;
  44989. /**
  44990. * Allows using an object space normal map (instead of tangent space).
  44991. */
  44992. _this.useObjectSpaceNormalMap = false;
  44993. /**
  44994. * Allows using the bump map in parallax mode.
  44995. */
  44996. _this.useParallax = false;
  44997. /**
  44998. * Allows using the bump map in parallax occlusion mode.
  44999. */
  45000. _this.useParallaxOcclusion = false;
  45001. /**
  45002. * Controls the scale bias of the parallax mode.
  45003. */
  45004. _this.parallaxScaleBias = 0.05;
  45005. /**
  45006. * If sets to true, disables all the lights affecting the material.
  45007. */
  45008. _this.disableLighting = false;
  45009. /**
  45010. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45011. */
  45012. _this.forceIrradianceInFragment = false;
  45013. /**
  45014. * Number of Simultaneous lights allowed on the material.
  45015. */
  45016. _this.maxSimultaneousLights = 4;
  45017. /**
  45018. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45019. */
  45020. _this.invertNormalMapX = false;
  45021. /**
  45022. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45023. */
  45024. _this.invertNormalMapY = false;
  45025. /**
  45026. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45027. */
  45028. _this.twoSidedLighting = false;
  45029. /**
  45030. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45031. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45032. */
  45033. _this.useAlphaFresnel = false;
  45034. /**
  45035. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45036. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45037. */
  45038. _this.useLinearAlphaFresnel = false;
  45039. /**
  45040. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45041. * And/Or occlude the blended part.
  45042. */
  45043. _this.environmentBRDFTexture = null;
  45044. /**
  45045. * Force normal to face away from face.
  45046. */
  45047. _this.forceNormalForward = false;
  45048. /**
  45049. * Enables specular anti aliasing in the PBR shader.
  45050. * It will both interacts on the Geometry for analytical and IBL lighting.
  45051. * It also prefilter the roughness map based on the bump values.
  45052. */
  45053. _this.enableSpecularAntiAliasing = false;
  45054. /**
  45055. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45056. * makes the reflect vector face the model (under horizon).
  45057. */
  45058. _this.useHorizonOcclusion = true;
  45059. /**
  45060. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45061. * too much the area relying on ambient texture to define their ambient occlusion.
  45062. */
  45063. _this.useRadianceOcclusion = true;
  45064. /**
  45065. * If set to true, no lighting calculations will be applied.
  45066. */
  45067. _this.unlit = false;
  45068. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45069. return _this;
  45070. }
  45071. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45072. /**
  45073. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45074. */
  45075. get: function () {
  45076. return this._PBRMATERIAL_OPAQUE;
  45077. },
  45078. enumerable: true,
  45079. configurable: true
  45080. });
  45081. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45082. /**
  45083. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45084. */
  45085. get: function () {
  45086. return this._PBRMATERIAL_ALPHATEST;
  45087. },
  45088. enumerable: true,
  45089. configurable: true
  45090. });
  45091. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45092. /**
  45093. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45094. */
  45095. get: function () {
  45096. return this._PBRMATERIAL_ALPHABLEND;
  45097. },
  45098. enumerable: true,
  45099. configurable: true
  45100. });
  45101. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45102. /**
  45103. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45104. * They are also discarded below the alpha cutoff threshold to improve performances.
  45105. */
  45106. get: function () {
  45107. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45108. },
  45109. enumerable: true,
  45110. configurable: true
  45111. });
  45112. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45113. /**
  45114. * Gets the image processing configuration used either in this material.
  45115. */
  45116. get: function () {
  45117. return this._imageProcessingConfiguration;
  45118. },
  45119. /**
  45120. * Sets the Default image processing configuration used either in the this material.
  45121. *
  45122. * If sets to null, the scene one is in use.
  45123. */
  45124. set: function (value) {
  45125. this._attachImageProcessingConfiguration(value);
  45126. // Ensure the effect will be rebuilt.
  45127. this._markAllSubMeshesAsTexturesDirty();
  45128. },
  45129. enumerable: true,
  45130. configurable: true
  45131. });
  45132. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45133. /**
  45134. * Gets wether the color curves effect is enabled.
  45135. */
  45136. get: function () {
  45137. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45138. },
  45139. /**
  45140. * Sets wether the color curves effect is enabled.
  45141. */
  45142. set: function (value) {
  45143. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45144. },
  45145. enumerable: true,
  45146. configurable: true
  45147. });
  45148. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45149. /**
  45150. * Gets wether the color grading effect is enabled.
  45151. */
  45152. get: function () {
  45153. return this.imageProcessingConfiguration.colorGradingEnabled;
  45154. },
  45155. /**
  45156. * Gets wether the color grading effect is enabled.
  45157. */
  45158. set: function (value) {
  45159. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45160. },
  45161. enumerable: true,
  45162. configurable: true
  45163. });
  45164. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45165. /**
  45166. * Gets wether tonemapping is enabled or not.
  45167. */
  45168. get: function () {
  45169. return this._imageProcessingConfiguration.toneMappingEnabled;
  45170. },
  45171. /**
  45172. * Sets wether tonemapping is enabled or not
  45173. */
  45174. set: function (value) {
  45175. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45176. },
  45177. enumerable: true,
  45178. configurable: true
  45179. });
  45180. ;
  45181. ;
  45182. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45183. /**
  45184. * The camera exposure used on this material.
  45185. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45186. * This corresponds to a photographic exposure.
  45187. */
  45188. get: function () {
  45189. return this._imageProcessingConfiguration.exposure;
  45190. },
  45191. /**
  45192. * The camera exposure used on this material.
  45193. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45194. * This corresponds to a photographic exposure.
  45195. */
  45196. set: function (value) {
  45197. this._imageProcessingConfiguration.exposure = value;
  45198. },
  45199. enumerable: true,
  45200. configurable: true
  45201. });
  45202. ;
  45203. ;
  45204. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45205. /**
  45206. * Gets The camera contrast used on this material.
  45207. */
  45208. get: function () {
  45209. return this._imageProcessingConfiguration.contrast;
  45210. },
  45211. /**
  45212. * Sets The camera contrast used on this material.
  45213. */
  45214. set: function (value) {
  45215. this._imageProcessingConfiguration.contrast = value;
  45216. },
  45217. enumerable: true,
  45218. configurable: true
  45219. });
  45220. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45221. /**
  45222. * Gets the Color Grading 2D Lookup Texture.
  45223. */
  45224. get: function () {
  45225. return this._imageProcessingConfiguration.colorGradingTexture;
  45226. },
  45227. /**
  45228. * Sets the Color Grading 2D Lookup Texture.
  45229. */
  45230. set: function (value) {
  45231. this._imageProcessingConfiguration.colorGradingTexture = value;
  45232. },
  45233. enumerable: true,
  45234. configurable: true
  45235. });
  45236. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45237. /**
  45238. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45239. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45240. * 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;
  45241. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45242. */
  45243. get: function () {
  45244. return this._imageProcessingConfiguration.colorCurves;
  45245. },
  45246. /**
  45247. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45248. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45249. * 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;
  45250. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45251. */
  45252. set: function (value) {
  45253. this._imageProcessingConfiguration.colorCurves = value;
  45254. },
  45255. enumerable: true,
  45256. configurable: true
  45257. });
  45258. /**
  45259. * Returns the name of this material class.
  45260. */
  45261. PBRMaterial.prototype.getClassName = function () {
  45262. return "PBRMaterial";
  45263. };
  45264. /**
  45265. * Returns an array of the actively used textures.
  45266. * @returns - Array of BaseTextures
  45267. */
  45268. PBRMaterial.prototype.getActiveTextures = function () {
  45269. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45270. if (this._albedoTexture) {
  45271. activeTextures.push(this._albedoTexture);
  45272. }
  45273. if (this._ambientTexture) {
  45274. activeTextures.push(this._ambientTexture);
  45275. }
  45276. if (this._opacityTexture) {
  45277. activeTextures.push(this._opacityTexture);
  45278. }
  45279. if (this._reflectionTexture) {
  45280. activeTextures.push(this._reflectionTexture);
  45281. }
  45282. if (this._emissiveTexture) {
  45283. activeTextures.push(this._emissiveTexture);
  45284. }
  45285. if (this._reflectivityTexture) {
  45286. activeTextures.push(this._reflectivityTexture);
  45287. }
  45288. if (this._metallicTexture) {
  45289. activeTextures.push(this._metallicTexture);
  45290. }
  45291. if (this._microSurfaceTexture) {
  45292. activeTextures.push(this._microSurfaceTexture);
  45293. }
  45294. if (this._bumpTexture) {
  45295. activeTextures.push(this._bumpTexture);
  45296. }
  45297. if (this._lightmapTexture) {
  45298. activeTextures.push(this._lightmapTexture);
  45299. }
  45300. if (this._refractionTexture) {
  45301. activeTextures.push(this._refractionTexture);
  45302. }
  45303. return activeTextures;
  45304. };
  45305. /**
  45306. * Checks to see if a texture is used in the material.
  45307. * @param texture - Base texture to use.
  45308. * @returns - Boolean specifying if a texture is used in the material.
  45309. */
  45310. PBRMaterial.prototype.hasTexture = function (texture) {
  45311. if (_super.prototype.hasTexture.call(this, texture)) {
  45312. return true;
  45313. }
  45314. if (this._albedoTexture === texture) {
  45315. return true;
  45316. }
  45317. if (this._ambientTexture === texture) {
  45318. return true;
  45319. }
  45320. if (this._opacityTexture === texture) {
  45321. return true;
  45322. }
  45323. if (this._reflectionTexture === texture) {
  45324. return true;
  45325. }
  45326. if (this._reflectivityTexture === texture) {
  45327. return true;
  45328. }
  45329. if (this._metallicTexture === texture) {
  45330. return true;
  45331. }
  45332. if (this._microSurfaceTexture === texture) {
  45333. return true;
  45334. }
  45335. if (this._bumpTexture === texture) {
  45336. return true;
  45337. }
  45338. if (this._lightmapTexture === texture) {
  45339. return true;
  45340. }
  45341. if (this._refractionTexture === texture) {
  45342. return true;
  45343. }
  45344. return false;
  45345. };
  45346. /**
  45347. * Makes a duplicate of the current material.
  45348. * @param name - name to use for the new material.
  45349. */
  45350. PBRMaterial.prototype.clone = function (name) {
  45351. var _this = this;
  45352. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45353. clone.id = name;
  45354. clone.name = name;
  45355. return clone;
  45356. };
  45357. /**
  45358. * Serializes this PBR Material.
  45359. * @returns - An object with the serialized material.
  45360. */
  45361. PBRMaterial.prototype.serialize = function () {
  45362. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45363. serializationObject.customType = "BABYLON.PBRMaterial";
  45364. return serializationObject;
  45365. };
  45366. // Statics
  45367. /**
  45368. * Parses a PBR Material from a serialized object.
  45369. * @param source - Serialized object.
  45370. * @param scene - BJS scene instance.
  45371. * @param rootUrl - url for the scene object
  45372. * @returns - PBRMaterial
  45373. */
  45374. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45375. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45376. };
  45377. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45378. /**
  45379. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45380. */
  45381. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45382. /**
  45383. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45384. */
  45385. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45386. /**
  45387. * 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.
  45388. * They are also discarded below the alpha cutoff threshold to improve performances.
  45389. */
  45390. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45391. __decorate([
  45392. BABYLON.serialize(),
  45393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45394. ], PBRMaterial.prototype, "directIntensity", void 0);
  45395. __decorate([
  45396. BABYLON.serialize(),
  45397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45398. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45399. __decorate([
  45400. BABYLON.serialize(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45402. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45407. __decorate([
  45408. BABYLON.serialize(),
  45409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45410. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45411. __decorate([
  45412. BABYLON.serializeAsTexture(),
  45413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45414. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45415. __decorate([
  45416. BABYLON.serializeAsTexture(),
  45417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45418. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45419. __decorate([
  45420. BABYLON.serialize(),
  45421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45422. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45423. __decorate([
  45424. BABYLON.serializeAsTexture(),
  45425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45426. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45427. __decorate([
  45428. BABYLON.serializeAsTexture(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45431. __decorate([
  45432. BABYLON.serializeAsTexture(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45434. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45435. __decorate([
  45436. BABYLON.serializeAsTexture(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45438. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45439. __decorate([
  45440. BABYLON.serializeAsTexture(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45442. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45443. __decorate([
  45444. BABYLON.serialize(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "metallic", void 0);
  45447. __decorate([
  45448. BABYLON.serialize(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "roughness", void 0);
  45451. __decorate([
  45452. BABYLON.serializeAsTexture(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45455. __decorate([
  45456. BABYLON.serializeAsTexture(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45459. __decorate([
  45460. BABYLON.serializeAsTexture(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45462. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsTexture(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45467. __decorate([
  45468. BABYLON.serializeAsColor3("ambient"),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "ambientColor", void 0);
  45471. __decorate([
  45472. BABYLON.serializeAsColor3("albedo"),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "albedoColor", void 0);
  45475. __decorate([
  45476. BABYLON.serializeAsColor3("reflectivity"),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45479. __decorate([
  45480. BABYLON.serializeAsColor3("reflection"),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45483. __decorate([
  45484. BABYLON.serializeAsColor3("emissive"),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45487. __decorate([
  45488. BABYLON.serialize(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "microSurface", void 0);
  45491. __decorate([
  45492. BABYLON.serialize(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45495. __decorate([
  45496. BABYLON.serialize(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45498. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45499. __decorate([
  45500. BABYLON.serialize(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45503. __decorate([
  45504. BABYLON.serialize(),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45507. __decorate([
  45508. BABYLON.serialize(),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45510. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45511. __decorate([
  45512. BABYLON.serialize(),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45514. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45515. __decorate([
  45516. BABYLON.serialize(),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45518. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45519. __decorate([
  45520. BABYLON.serialize(),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45527. __decorate([
  45528. BABYLON.serialize(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45546. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45550. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45554. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "useParallax", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45578. ], PBRMaterial.prototype, "disableLighting", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45586. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45607. __decorate([
  45608. BABYLON.serializeAsTexture(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45630. ], PBRMaterial.prototype, "unlit", void 0);
  45631. return PBRMaterial;
  45632. }(BABYLON.PBRBaseMaterial));
  45633. BABYLON.PBRMaterial = PBRMaterial;
  45634. })(BABYLON || (BABYLON = {}));
  45635. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45636. var BABYLON;
  45637. (function (BABYLON) {
  45638. /**
  45639. * The PBR material of BJS following the metal roughness convention.
  45640. *
  45641. * This fits to the PBR convention in the GLTF definition:
  45642. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45643. */
  45644. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45645. __extends(PBRMetallicRoughnessMaterial, _super);
  45646. /**
  45647. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45648. *
  45649. * @param name The material name
  45650. * @param scene The scene the material will be use in.
  45651. */
  45652. function PBRMetallicRoughnessMaterial(name, scene) {
  45653. var _this = _super.call(this, name, scene) || this;
  45654. _this._useRoughnessFromMetallicTextureAlpha = false;
  45655. _this._useRoughnessFromMetallicTextureGreen = true;
  45656. _this._useMetallnessFromMetallicTextureBlue = true;
  45657. _this.metallic = 1.0;
  45658. _this.roughness = 1.0;
  45659. return _this;
  45660. }
  45661. /**
  45662. * Return the currrent class name of the material.
  45663. */
  45664. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45665. return "PBRMetallicRoughnessMaterial";
  45666. };
  45667. /**
  45668. * Return the active textures of the material.
  45669. */
  45670. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45671. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45672. if (this.baseTexture) {
  45673. activeTextures.push(this.baseTexture);
  45674. }
  45675. if (this.metallicRoughnessTexture) {
  45676. activeTextures.push(this.metallicRoughnessTexture);
  45677. }
  45678. return activeTextures;
  45679. };
  45680. /**
  45681. * Checks to see if a texture is used in the material.
  45682. * @param texture - Base texture to use.
  45683. * @returns - Boolean specifying if a texture is used in the material.
  45684. */
  45685. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45686. if (_super.prototype.hasTexture.call(this, texture)) {
  45687. return true;
  45688. }
  45689. if (this.baseTexture === texture) {
  45690. return true;
  45691. }
  45692. if (this.metallicRoughnessTexture === texture) {
  45693. return true;
  45694. }
  45695. return false;
  45696. };
  45697. /**
  45698. * Makes a duplicate of the current material.
  45699. * @param name - name to use for the new material.
  45700. */
  45701. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45702. var _this = this;
  45703. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45704. clone.id = name;
  45705. clone.name = name;
  45706. return clone;
  45707. };
  45708. /**
  45709. * Serialize the material to a parsable JSON object.
  45710. */
  45711. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45713. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45714. return serializationObject;
  45715. };
  45716. /**
  45717. * Parses a JSON object correponding to the serialize function.
  45718. */
  45719. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45720. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45721. };
  45722. __decorate([
  45723. BABYLON.serializeAsColor3(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45725. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45726. __decorate([
  45727. BABYLON.serializeAsTexture(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45729. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45737. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45738. __decorate([
  45739. BABYLON.serializeAsTexture(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45741. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45742. return PBRMetallicRoughnessMaterial;
  45743. }(BABYLON.PBRBaseSimpleMaterial));
  45744. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45745. })(BABYLON || (BABYLON = {}));
  45746. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45747. var BABYLON;
  45748. (function (BABYLON) {
  45749. /**
  45750. * The PBR material of BJS following the specular glossiness convention.
  45751. *
  45752. * This fits to the PBR convention in the GLTF definition:
  45753. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45754. */
  45755. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45756. __extends(PBRSpecularGlossinessMaterial, _super);
  45757. /**
  45758. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45759. *
  45760. * @param name The material name
  45761. * @param scene The scene the material will be use in.
  45762. */
  45763. function PBRSpecularGlossinessMaterial(name, scene) {
  45764. var _this = _super.call(this, name, scene) || this;
  45765. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45766. return _this;
  45767. }
  45768. /**
  45769. * Return the currrent class name of the material.
  45770. */
  45771. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45772. return "PBRSpecularGlossinessMaterial";
  45773. };
  45774. /**
  45775. * Return the active textures of the material.
  45776. */
  45777. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45778. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45779. if (this.diffuseTexture) {
  45780. activeTextures.push(this.diffuseTexture);
  45781. }
  45782. if (this.specularGlossinessTexture) {
  45783. activeTextures.push(this.specularGlossinessTexture);
  45784. }
  45785. return activeTextures;
  45786. };
  45787. /**
  45788. * Checks to see if a texture is used in the material.
  45789. * @param texture - Base texture to use.
  45790. * @returns - Boolean specifying if a texture is used in the material.
  45791. */
  45792. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45793. if (_super.prototype.hasTexture.call(this, texture)) {
  45794. return true;
  45795. }
  45796. if (this.diffuseTexture === texture) {
  45797. return true;
  45798. }
  45799. if (this.specularGlossinessTexture === texture) {
  45800. return true;
  45801. }
  45802. return false;
  45803. };
  45804. /**
  45805. * Makes a duplicate of the current material.
  45806. * @param name - name to use for the new material.
  45807. */
  45808. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45809. var _this = this;
  45810. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45811. clone.id = name;
  45812. clone.name = name;
  45813. return clone;
  45814. };
  45815. /**
  45816. * Serialize the material to a parsable JSON object.
  45817. */
  45818. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45819. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45820. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45821. return serializationObject;
  45822. };
  45823. /**
  45824. * Parses a JSON object correponding to the serialize function.
  45825. */
  45826. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45827. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45828. };
  45829. __decorate([
  45830. BABYLON.serializeAsColor3("diffuse"),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45832. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45833. __decorate([
  45834. BABYLON.serializeAsTexture(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45836. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45837. __decorate([
  45838. BABYLON.serializeAsColor3("specular"),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45840. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45841. __decorate([
  45842. BABYLON.serialize(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45844. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45845. __decorate([
  45846. BABYLON.serializeAsTexture(),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45848. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45849. return PBRSpecularGlossinessMaterial;
  45850. }(BABYLON.PBRBaseSimpleMaterial));
  45851. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45852. })(BABYLON || (BABYLON = {}));
  45853. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45854. var BABYLON;
  45855. (function (BABYLON) {
  45856. BABYLON.CameraInputTypes = {};
  45857. var CameraInputsManager = /** @class */ (function () {
  45858. function CameraInputsManager(camera) {
  45859. this.attached = {};
  45860. this.camera = camera;
  45861. this.checkInputs = function () { };
  45862. }
  45863. /**
  45864. * Add an input method to a camera.
  45865. * builtin inputs example: camera.inputs.addGamepad();
  45866. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45867. * @param input camera input method
  45868. */
  45869. CameraInputsManager.prototype.add = function (input) {
  45870. var type = input.getSimpleName();
  45871. if (this.attached[type]) {
  45872. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45873. return;
  45874. }
  45875. this.attached[type] = input;
  45876. input.camera = this.camera;
  45877. //for checkInputs, we are dynamically creating a function
  45878. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45879. if (input.checkInputs) {
  45880. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45881. }
  45882. if (this.attachedElement) {
  45883. input.attachControl(this.attachedElement);
  45884. }
  45885. };
  45886. /**
  45887. * Remove a specific input method from a camera
  45888. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45889. * @param inputToRemove camera input method
  45890. */
  45891. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45892. for (var cam in this.attached) {
  45893. var input = this.attached[cam];
  45894. if (input === inputToRemove) {
  45895. input.detachControl(this.attachedElement);
  45896. input.camera = null;
  45897. delete this.attached[cam];
  45898. this.rebuildInputCheck();
  45899. }
  45900. }
  45901. };
  45902. CameraInputsManager.prototype.removeByType = function (inputType) {
  45903. for (var cam in this.attached) {
  45904. var input = this.attached[cam];
  45905. if (input.getClassName() === inputType) {
  45906. input.detachControl(this.attachedElement);
  45907. input.camera = null;
  45908. delete this.attached[cam];
  45909. this.rebuildInputCheck();
  45910. }
  45911. }
  45912. };
  45913. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45914. var current = this.checkInputs;
  45915. return function () {
  45916. current();
  45917. fn();
  45918. };
  45919. };
  45920. CameraInputsManager.prototype.attachInput = function (input) {
  45921. if (this.attachedElement) {
  45922. input.attachControl(this.attachedElement, this.noPreventDefault);
  45923. }
  45924. };
  45925. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45926. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45927. if (this.attachedElement) {
  45928. return;
  45929. }
  45930. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45931. this.attachedElement = element;
  45932. this.noPreventDefault = noPreventDefault;
  45933. for (var cam in this.attached) {
  45934. this.attached[cam].attachControl(element, noPreventDefault);
  45935. }
  45936. };
  45937. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45938. if (disconnect === void 0) { disconnect = false; }
  45939. if (this.attachedElement !== element) {
  45940. return;
  45941. }
  45942. for (var cam in this.attached) {
  45943. this.attached[cam].detachControl(element);
  45944. if (disconnect) {
  45945. this.attached[cam].camera = null;
  45946. }
  45947. }
  45948. this.attachedElement = null;
  45949. };
  45950. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45951. this.checkInputs = function () { };
  45952. for (var cam in this.attached) {
  45953. var input = this.attached[cam];
  45954. if (input.checkInputs) {
  45955. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45956. }
  45957. }
  45958. };
  45959. /**
  45960. * Remove all attached input methods from a camera
  45961. */
  45962. CameraInputsManager.prototype.clear = function () {
  45963. if (this.attachedElement) {
  45964. this.detachElement(this.attachedElement, true);
  45965. }
  45966. this.attached = {};
  45967. this.attachedElement = null;
  45968. this.checkInputs = function () { };
  45969. };
  45970. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45971. var inputs = {};
  45972. for (var cam in this.attached) {
  45973. var input = this.attached[cam];
  45974. var res = BABYLON.SerializationHelper.Serialize(input);
  45975. inputs[input.getClassName()] = res;
  45976. }
  45977. serializedCamera.inputsmgr = inputs;
  45978. };
  45979. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45980. var parsedInputs = parsedCamera.inputsmgr;
  45981. if (parsedInputs) {
  45982. this.clear();
  45983. for (var n in parsedInputs) {
  45984. var construct = BABYLON.CameraInputTypes[n];
  45985. if (construct) {
  45986. var parsedinput = parsedInputs[n];
  45987. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45988. this.add(input);
  45989. }
  45990. }
  45991. }
  45992. else {
  45993. //2016-03-08 this part is for managing backward compatibility
  45994. for (var n in this.attached) {
  45995. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45996. if (construct) {
  45997. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45998. this.remove(this.attached[n]);
  45999. this.add(input);
  46000. }
  46001. }
  46002. }
  46003. };
  46004. return CameraInputsManager;
  46005. }());
  46006. BABYLON.CameraInputsManager = CameraInputsManager;
  46007. })(BABYLON || (BABYLON = {}));
  46008. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46009. var BABYLON;
  46010. (function (BABYLON) {
  46011. var TargetCamera = /** @class */ (function (_super) {
  46012. __extends(TargetCamera, _super);
  46013. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46014. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46015. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46016. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46017. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46018. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46019. _this.speed = 2.0;
  46020. _this.noRotationConstraint = false;
  46021. _this.lockedTarget = null;
  46022. _this._currentTarget = BABYLON.Vector3.Zero();
  46023. _this._viewMatrix = BABYLON.Matrix.Zero();
  46024. _this._camMatrix = BABYLON.Matrix.Zero();
  46025. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46026. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46027. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46028. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46029. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46030. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46031. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46032. return _this;
  46033. }
  46034. TargetCamera.prototype.getFrontPosition = function (distance) {
  46035. this.getWorldMatrix();
  46036. var direction = this.getTarget().subtract(this.position);
  46037. direction.normalize();
  46038. direction.scaleInPlace(distance);
  46039. return this.globalPosition.add(direction);
  46040. };
  46041. TargetCamera.prototype._getLockedTargetPosition = function () {
  46042. if (!this.lockedTarget) {
  46043. return null;
  46044. }
  46045. if (this.lockedTarget.absolutePosition) {
  46046. this.lockedTarget.computeWorldMatrix();
  46047. }
  46048. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46049. };
  46050. TargetCamera.prototype.storeState = function () {
  46051. this._storedPosition = this.position.clone();
  46052. this._storedRotation = this.rotation.clone();
  46053. if (this.rotationQuaternion) {
  46054. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46055. }
  46056. return _super.prototype.storeState.call(this);
  46057. };
  46058. /**
  46059. * Restored camera state. You must call storeState() first
  46060. */
  46061. TargetCamera.prototype._restoreStateValues = function () {
  46062. if (!_super.prototype._restoreStateValues.call(this)) {
  46063. return false;
  46064. }
  46065. this.position = this._storedPosition.clone();
  46066. this.rotation = this._storedRotation.clone();
  46067. if (this.rotationQuaternion) {
  46068. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46069. }
  46070. this.cameraDirection.copyFromFloats(0, 0, 0);
  46071. this.cameraRotation.copyFromFloats(0, 0);
  46072. return true;
  46073. };
  46074. // Cache
  46075. TargetCamera.prototype._initCache = function () {
  46076. _super.prototype._initCache.call(this);
  46077. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46078. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46079. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46080. };
  46081. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46082. if (!ignoreParentClass) {
  46083. _super.prototype._updateCache.call(this);
  46084. }
  46085. var lockedTargetPosition = this._getLockedTargetPosition();
  46086. if (!lockedTargetPosition) {
  46087. this._cache.lockedTarget = null;
  46088. }
  46089. else {
  46090. if (!this._cache.lockedTarget) {
  46091. this._cache.lockedTarget = lockedTargetPosition.clone();
  46092. }
  46093. else {
  46094. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46095. }
  46096. }
  46097. this._cache.rotation.copyFrom(this.rotation);
  46098. if (this.rotationQuaternion)
  46099. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46100. };
  46101. // Synchronized
  46102. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46103. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46104. return false;
  46105. }
  46106. var lockedTargetPosition = this._getLockedTargetPosition();
  46107. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46108. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46109. };
  46110. // Methods
  46111. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46112. var engine = this.getEngine();
  46113. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46114. };
  46115. // Target
  46116. TargetCamera.prototype.setTarget = function (target) {
  46117. this.upVector.normalize();
  46118. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46119. this._camMatrix.invert();
  46120. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46121. var vDir = target.subtract(this.position);
  46122. if (vDir.x >= 0.0) {
  46123. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46124. }
  46125. else {
  46126. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46127. }
  46128. this.rotation.z = 0;
  46129. if (isNaN(this.rotation.x)) {
  46130. this.rotation.x = 0;
  46131. }
  46132. if (isNaN(this.rotation.y)) {
  46133. this.rotation.y = 0;
  46134. }
  46135. if (isNaN(this.rotation.z)) {
  46136. this.rotation.z = 0;
  46137. }
  46138. if (this.rotationQuaternion) {
  46139. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46140. }
  46141. };
  46142. /**
  46143. * Return the current target position of the camera. This value is expressed in local space.
  46144. */
  46145. TargetCamera.prototype.getTarget = function () {
  46146. return this._currentTarget;
  46147. };
  46148. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46149. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46150. };
  46151. TargetCamera.prototype._updatePosition = function () {
  46152. if (this.parent) {
  46153. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46154. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46155. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46156. return;
  46157. }
  46158. this.position.addInPlace(this.cameraDirection);
  46159. };
  46160. TargetCamera.prototype._checkInputs = function () {
  46161. var needToMove = this._decideIfNeedsToMove();
  46162. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46163. // Move
  46164. if (needToMove) {
  46165. this._updatePosition();
  46166. }
  46167. // Rotate
  46168. if (needToRotate) {
  46169. this.rotation.x += this.cameraRotation.x;
  46170. this.rotation.y += this.cameraRotation.y;
  46171. //rotate, if quaternion is set and rotation was used
  46172. if (this.rotationQuaternion) {
  46173. var len = this.rotation.lengthSquared();
  46174. if (len) {
  46175. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46176. }
  46177. }
  46178. if (!this.noRotationConstraint) {
  46179. var limit = (Math.PI / 2) * 0.95;
  46180. if (this.rotation.x > limit)
  46181. this.rotation.x = limit;
  46182. if (this.rotation.x < -limit)
  46183. this.rotation.x = -limit;
  46184. }
  46185. }
  46186. // Inertia
  46187. if (needToMove) {
  46188. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46189. this.cameraDirection.x = 0;
  46190. }
  46191. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46192. this.cameraDirection.y = 0;
  46193. }
  46194. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46195. this.cameraDirection.z = 0;
  46196. }
  46197. this.cameraDirection.scaleInPlace(this.inertia);
  46198. }
  46199. if (needToRotate) {
  46200. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46201. this.cameraRotation.x = 0;
  46202. }
  46203. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46204. this.cameraRotation.y = 0;
  46205. }
  46206. this.cameraRotation.scaleInPlace(this.inertia);
  46207. }
  46208. _super.prototype._checkInputs.call(this);
  46209. };
  46210. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46211. if (this.rotationQuaternion) {
  46212. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46213. }
  46214. else {
  46215. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46216. }
  46217. //update the up vector!
  46218. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46219. };
  46220. TargetCamera.prototype._getViewMatrix = function () {
  46221. if (this.lockedTarget) {
  46222. this.setTarget(this._getLockedTargetPosition());
  46223. }
  46224. // Compute
  46225. this._updateCameraRotationMatrix();
  46226. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46227. // Computing target and final matrix
  46228. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46229. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46230. return this._viewMatrix;
  46231. };
  46232. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46233. if (this.parent) {
  46234. var parentWorldMatrix = this.parent.getWorldMatrix();
  46235. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46236. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46237. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46238. this._markSyncedWithParent();
  46239. }
  46240. else {
  46241. this._globalPosition.copyFrom(this.position);
  46242. this._globalCurrentTarget.copyFrom(target);
  46243. this._globalCurrentUpVector.copyFrom(up);
  46244. }
  46245. if (this.getScene().useRightHandedSystem) {
  46246. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46247. }
  46248. else {
  46249. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46250. }
  46251. };
  46252. /**
  46253. * @override
  46254. * Override Camera.createRigCamera
  46255. */
  46256. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46257. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46258. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46259. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46260. if (!this.rotationQuaternion) {
  46261. this.rotationQuaternion = new BABYLON.Quaternion();
  46262. }
  46263. rigCamera._cameraRigParams = {};
  46264. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46265. }
  46266. return rigCamera;
  46267. }
  46268. return null;
  46269. };
  46270. /**
  46271. * @override
  46272. * Override Camera._updateRigCameras
  46273. */
  46274. TargetCamera.prototype._updateRigCameras = function () {
  46275. var camLeft = this._rigCameras[0];
  46276. var camRight = this._rigCameras[1];
  46277. switch (this.cameraRigMode) {
  46278. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46279. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46280. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46281. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46282. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46283. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46284. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46285. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46286. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46287. camLeft.setTarget(this.getTarget());
  46288. camRight.setTarget(this.getTarget());
  46289. break;
  46290. case BABYLON.Camera.RIG_MODE_VR:
  46291. if (camLeft.rotationQuaternion) {
  46292. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46293. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46294. }
  46295. else {
  46296. camLeft.rotation.copyFrom(this.rotation);
  46297. camRight.rotation.copyFrom(this.rotation);
  46298. }
  46299. camLeft.position.copyFrom(this.position);
  46300. camRight.position.copyFrom(this.position);
  46301. break;
  46302. }
  46303. _super.prototype._updateRigCameras.call(this);
  46304. };
  46305. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46306. if (!this._rigCamTransformMatrix) {
  46307. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46308. }
  46309. var target = this.getTarget();
  46310. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46311. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46312. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46313. };
  46314. TargetCamera.prototype.getClassName = function () {
  46315. return "TargetCamera";
  46316. };
  46317. __decorate([
  46318. BABYLON.serializeAsVector3()
  46319. ], TargetCamera.prototype, "rotation", void 0);
  46320. __decorate([
  46321. BABYLON.serialize()
  46322. ], TargetCamera.prototype, "speed", void 0);
  46323. __decorate([
  46324. BABYLON.serializeAsMeshReference("lockedTargetId")
  46325. ], TargetCamera.prototype, "lockedTarget", void 0);
  46326. return TargetCamera;
  46327. }(BABYLON.Camera));
  46328. BABYLON.TargetCamera = TargetCamera;
  46329. })(BABYLON || (BABYLON = {}));
  46330. //# sourceMappingURL=babylon.targetCamera.js.map
  46331. var BABYLON;
  46332. (function (BABYLON) {
  46333. var FreeCameraMouseInput = /** @class */ (function () {
  46334. function FreeCameraMouseInput(touchEnabled) {
  46335. if (touchEnabled === void 0) { touchEnabled = true; }
  46336. this.touchEnabled = touchEnabled;
  46337. this.buttons = [0, 1, 2];
  46338. this.angularSensibility = 2000.0;
  46339. this.previousPosition = null;
  46340. }
  46341. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46342. var _this = this;
  46343. var engine = this.camera.getEngine();
  46344. if (!this._pointerInput) {
  46345. this._pointerInput = function (p, s) {
  46346. var evt = p.event;
  46347. if (engine.isInVRExclusivePointerMode) {
  46348. return;
  46349. }
  46350. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46351. return;
  46352. }
  46353. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46354. return;
  46355. }
  46356. var srcElement = (evt.srcElement || evt.target);
  46357. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46358. try {
  46359. srcElement.setPointerCapture(evt.pointerId);
  46360. }
  46361. catch (e) {
  46362. //Nothing to do with the error. Execution will continue.
  46363. }
  46364. _this.previousPosition = {
  46365. x: evt.clientX,
  46366. y: evt.clientY
  46367. };
  46368. if (!noPreventDefault) {
  46369. evt.preventDefault();
  46370. element.focus();
  46371. }
  46372. }
  46373. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46374. try {
  46375. srcElement.releasePointerCapture(evt.pointerId);
  46376. }
  46377. catch (e) {
  46378. //Nothing to do with the error.
  46379. }
  46380. _this.previousPosition = null;
  46381. if (!noPreventDefault) {
  46382. evt.preventDefault();
  46383. }
  46384. }
  46385. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46386. if (!_this.previousPosition || engine.isPointerLock) {
  46387. return;
  46388. }
  46389. var offsetX = evt.clientX - _this.previousPosition.x;
  46390. if (_this.camera.getScene().useRightHandedSystem)
  46391. offsetX *= -1;
  46392. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46393. offsetX *= -1;
  46394. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46395. var offsetY = evt.clientY - _this.previousPosition.y;
  46396. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46397. _this.previousPosition = {
  46398. x: evt.clientX,
  46399. y: evt.clientY
  46400. };
  46401. if (!noPreventDefault) {
  46402. evt.preventDefault();
  46403. }
  46404. }
  46405. };
  46406. }
  46407. this._onMouseMove = function (evt) {
  46408. if (!engine.isPointerLock) {
  46409. return;
  46410. }
  46411. if (engine.isInVRExclusivePointerMode) {
  46412. return;
  46413. }
  46414. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46415. if (_this.camera.getScene().useRightHandedSystem)
  46416. offsetX *= -1;
  46417. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46418. offsetX *= -1;
  46419. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46420. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46421. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46422. _this.previousPosition = null;
  46423. if (!noPreventDefault) {
  46424. evt.preventDefault();
  46425. }
  46426. };
  46427. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46428. element.addEventListener("mousemove", this._onMouseMove, false);
  46429. };
  46430. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46431. if (this._observer && element) {
  46432. this.camera.getScene().onPointerObservable.remove(this._observer);
  46433. if (this._onMouseMove) {
  46434. element.removeEventListener("mousemove", this._onMouseMove);
  46435. }
  46436. this._observer = null;
  46437. this._onMouseMove = null;
  46438. this.previousPosition = null;
  46439. }
  46440. };
  46441. FreeCameraMouseInput.prototype.getClassName = function () {
  46442. return "FreeCameraMouseInput";
  46443. };
  46444. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46445. return "mouse";
  46446. };
  46447. __decorate([
  46448. BABYLON.serialize()
  46449. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46450. __decorate([
  46451. BABYLON.serialize()
  46452. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46453. return FreeCameraMouseInput;
  46454. }());
  46455. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46456. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46457. })(BABYLON || (BABYLON = {}));
  46458. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46459. var BABYLON;
  46460. (function (BABYLON) {
  46461. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46462. function FreeCameraKeyboardMoveInput() {
  46463. this._keys = new Array();
  46464. this.keysUp = [38];
  46465. this.keysDown = [40];
  46466. this.keysLeft = [37];
  46467. this.keysRight = [39];
  46468. }
  46469. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46470. var _this = this;
  46471. if (this._onCanvasBlurObserver) {
  46472. return;
  46473. }
  46474. this._scene = this.camera.getScene();
  46475. this._engine = this._scene.getEngine();
  46476. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46477. _this._keys = [];
  46478. });
  46479. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46480. var evt = info.event;
  46481. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46482. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46483. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46484. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46485. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46486. var index = _this._keys.indexOf(evt.keyCode);
  46487. if (index === -1) {
  46488. _this._keys.push(evt.keyCode);
  46489. }
  46490. if (!noPreventDefault) {
  46491. evt.preventDefault();
  46492. }
  46493. }
  46494. }
  46495. else {
  46496. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46497. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46498. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46499. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46500. var index = _this._keys.indexOf(evt.keyCode);
  46501. if (index >= 0) {
  46502. _this._keys.splice(index, 1);
  46503. }
  46504. if (!noPreventDefault) {
  46505. evt.preventDefault();
  46506. }
  46507. }
  46508. }
  46509. });
  46510. };
  46511. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46512. if (this._scene) {
  46513. if (this._onKeyboardObserver) {
  46514. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46515. }
  46516. if (this._onCanvasBlurObserver) {
  46517. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46518. }
  46519. this._onKeyboardObserver = null;
  46520. this._onCanvasBlurObserver = null;
  46521. }
  46522. this._keys = [];
  46523. };
  46524. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46525. if (this._onKeyboardObserver) {
  46526. var camera = this.camera;
  46527. // Keyboard
  46528. for (var index = 0; index < this._keys.length; index++) {
  46529. var keyCode = this._keys[index];
  46530. var speed = camera._computeLocalCameraSpeed();
  46531. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46532. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46533. }
  46534. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46535. camera._localDirection.copyFromFloats(0, 0, speed);
  46536. }
  46537. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46538. camera._localDirection.copyFromFloats(speed, 0, 0);
  46539. }
  46540. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46541. camera._localDirection.copyFromFloats(0, 0, -speed);
  46542. }
  46543. if (camera.getScene().useRightHandedSystem) {
  46544. camera._localDirection.z *= -1;
  46545. }
  46546. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46547. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46548. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46549. }
  46550. }
  46551. };
  46552. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46553. return "FreeCameraKeyboardMoveInput";
  46554. };
  46555. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46556. this._keys = [];
  46557. };
  46558. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46559. return "keyboard";
  46560. };
  46561. __decorate([
  46562. BABYLON.serialize()
  46563. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46564. __decorate([
  46565. BABYLON.serialize()
  46566. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46567. __decorate([
  46568. BABYLON.serialize()
  46569. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46570. __decorate([
  46571. BABYLON.serialize()
  46572. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46573. return FreeCameraKeyboardMoveInput;
  46574. }());
  46575. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46576. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46577. })(BABYLON || (BABYLON = {}));
  46578. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46579. var BABYLON;
  46580. (function (BABYLON) {
  46581. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46582. __extends(FreeCameraInputsManager, _super);
  46583. function FreeCameraInputsManager(camera) {
  46584. return _super.call(this, camera) || this;
  46585. }
  46586. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46587. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46588. return this;
  46589. };
  46590. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46591. if (touchEnabled === void 0) { touchEnabled = true; }
  46592. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46593. return this;
  46594. };
  46595. FreeCameraInputsManager.prototype.addGamepad = function () {
  46596. this.add(new BABYLON.FreeCameraGamepadInput());
  46597. return this;
  46598. };
  46599. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46600. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46601. return this;
  46602. };
  46603. FreeCameraInputsManager.prototype.addTouch = function () {
  46604. this.add(new BABYLON.FreeCameraTouchInput());
  46605. return this;
  46606. };
  46607. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46608. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46609. return this;
  46610. };
  46611. return FreeCameraInputsManager;
  46612. }(BABYLON.CameraInputsManager));
  46613. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46614. })(BABYLON || (BABYLON = {}));
  46615. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46616. var BABYLON;
  46617. (function (BABYLON) {
  46618. var FreeCamera = /** @class */ (function (_super) {
  46619. __extends(FreeCamera, _super);
  46620. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46621. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46622. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46623. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46624. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46625. _this.checkCollisions = false;
  46626. _this.applyGravity = false;
  46627. _this._needMoveForGravity = false;
  46628. _this._oldPosition = BABYLON.Vector3.Zero();
  46629. _this._diffPosition = BABYLON.Vector3.Zero();
  46630. _this._newPosition = BABYLON.Vector3.Zero();
  46631. // Collisions
  46632. _this._collisionMask = -1;
  46633. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46634. if (collidedMesh === void 0) { collidedMesh = null; }
  46635. //TODO move this to the collision coordinator!
  46636. if (_this.getScene().workerCollisions)
  46637. newPosition.multiplyInPlace(_this._collider._radius);
  46638. var updatePosition = function (newPos) {
  46639. _this._newPosition.copyFrom(newPos);
  46640. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46641. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46642. _this.position.addInPlace(_this._diffPosition);
  46643. if (_this.onCollide && collidedMesh) {
  46644. _this.onCollide(collidedMesh);
  46645. }
  46646. }
  46647. };
  46648. updatePosition(newPosition);
  46649. };
  46650. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46651. _this.inputs.addKeyboard().addMouse();
  46652. return _this;
  46653. }
  46654. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46655. //-- begin properties for backward compatibility for inputs
  46656. /**
  46657. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46658. * Higher values reduce sensitivity.
  46659. */
  46660. get: function () {
  46661. var mouse = this.inputs.attached["mouse"];
  46662. if (mouse)
  46663. return mouse.angularSensibility;
  46664. return 0;
  46665. },
  46666. /**
  46667. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46668. * Higher values reduce sensitivity.
  46669. */
  46670. set: function (value) {
  46671. var mouse = this.inputs.attached["mouse"];
  46672. if (mouse)
  46673. mouse.angularSensibility = value;
  46674. },
  46675. enumerable: true,
  46676. configurable: true
  46677. });
  46678. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46679. get: function () {
  46680. var keyboard = this.inputs.attached["keyboard"];
  46681. if (keyboard)
  46682. return keyboard.keysUp;
  46683. return [];
  46684. },
  46685. set: function (value) {
  46686. var keyboard = this.inputs.attached["keyboard"];
  46687. if (keyboard)
  46688. keyboard.keysUp = value;
  46689. },
  46690. enumerable: true,
  46691. configurable: true
  46692. });
  46693. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46694. get: function () {
  46695. var keyboard = this.inputs.attached["keyboard"];
  46696. if (keyboard)
  46697. return keyboard.keysDown;
  46698. return [];
  46699. },
  46700. set: function (value) {
  46701. var keyboard = this.inputs.attached["keyboard"];
  46702. if (keyboard)
  46703. keyboard.keysDown = value;
  46704. },
  46705. enumerable: true,
  46706. configurable: true
  46707. });
  46708. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46709. get: function () {
  46710. var keyboard = this.inputs.attached["keyboard"];
  46711. if (keyboard)
  46712. return keyboard.keysLeft;
  46713. return [];
  46714. },
  46715. set: function (value) {
  46716. var keyboard = this.inputs.attached["keyboard"];
  46717. if (keyboard)
  46718. keyboard.keysLeft = value;
  46719. },
  46720. enumerable: true,
  46721. configurable: true
  46722. });
  46723. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46724. get: function () {
  46725. var keyboard = this.inputs.attached["keyboard"];
  46726. if (keyboard)
  46727. return keyboard.keysRight;
  46728. return [];
  46729. },
  46730. set: function (value) {
  46731. var keyboard = this.inputs.attached["keyboard"];
  46732. if (keyboard)
  46733. keyboard.keysRight = value;
  46734. },
  46735. enumerable: true,
  46736. configurable: true
  46737. });
  46738. // Controls
  46739. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46740. this.inputs.attachElement(element, noPreventDefault);
  46741. };
  46742. FreeCamera.prototype.detachControl = function (element) {
  46743. this.inputs.detachElement(element);
  46744. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46745. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46746. };
  46747. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46748. get: function () {
  46749. return this._collisionMask;
  46750. },
  46751. set: function (mask) {
  46752. this._collisionMask = !isNaN(mask) ? mask : -1;
  46753. },
  46754. enumerable: true,
  46755. configurable: true
  46756. });
  46757. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46758. var globalPosition;
  46759. if (this.parent) {
  46760. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46761. }
  46762. else {
  46763. globalPosition = this.position;
  46764. }
  46765. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46766. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46767. if (!this._collider) {
  46768. this._collider = new BABYLON.Collider();
  46769. }
  46770. this._collider._radius = this.ellipsoid;
  46771. this._collider.collisionMask = this._collisionMask;
  46772. //no need for clone, as long as gravity is not on.
  46773. var actualDisplacement = displacement;
  46774. //add gravity to the direction to prevent the dual-collision checking
  46775. if (this.applyGravity) {
  46776. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46777. actualDisplacement = displacement.add(this.getScene().gravity);
  46778. }
  46779. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46780. };
  46781. FreeCamera.prototype._checkInputs = function () {
  46782. if (!this._localDirection) {
  46783. this._localDirection = BABYLON.Vector3.Zero();
  46784. this._transformedDirection = BABYLON.Vector3.Zero();
  46785. }
  46786. this.inputs.checkInputs();
  46787. _super.prototype._checkInputs.call(this);
  46788. };
  46789. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46790. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46791. };
  46792. FreeCamera.prototype._updatePosition = function () {
  46793. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46794. this._collideWithWorld(this.cameraDirection);
  46795. }
  46796. else {
  46797. _super.prototype._updatePosition.call(this);
  46798. }
  46799. };
  46800. FreeCamera.prototype.dispose = function () {
  46801. this.inputs.clear();
  46802. _super.prototype.dispose.call(this);
  46803. };
  46804. FreeCamera.prototype.getClassName = function () {
  46805. return "FreeCamera";
  46806. };
  46807. __decorate([
  46808. BABYLON.serializeAsVector3()
  46809. ], FreeCamera.prototype, "ellipsoid", void 0);
  46810. __decorate([
  46811. BABYLON.serializeAsVector3()
  46812. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46813. __decorate([
  46814. BABYLON.serialize()
  46815. ], FreeCamera.prototype, "checkCollisions", void 0);
  46816. __decorate([
  46817. BABYLON.serialize()
  46818. ], FreeCamera.prototype, "applyGravity", void 0);
  46819. return FreeCamera;
  46820. }(BABYLON.TargetCamera));
  46821. BABYLON.FreeCamera = FreeCamera;
  46822. })(BABYLON || (BABYLON = {}));
  46823. //# sourceMappingURL=babylon.freeCamera.js.map
  46824. var BABYLON;
  46825. (function (BABYLON) {
  46826. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46827. function ArcRotateCameraKeyboardMoveInput() {
  46828. this._keys = new Array();
  46829. this.keysUp = [38];
  46830. this.keysDown = [40];
  46831. this.keysLeft = [37];
  46832. this.keysRight = [39];
  46833. this.keysReset = [220];
  46834. this.panningSensibility = 50.0;
  46835. this.zoomingSensibility = 25.0;
  46836. this.useAltToZoom = true;
  46837. }
  46838. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46839. var _this = this;
  46840. if (this._onCanvasBlurObserver) {
  46841. return;
  46842. }
  46843. this._scene = this.camera.getScene();
  46844. this._engine = this._scene.getEngine();
  46845. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46846. _this._keys = [];
  46847. });
  46848. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46849. var evt = info.event;
  46850. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46851. _this._ctrlPressed = evt.ctrlKey;
  46852. _this._altPressed = evt.altKey;
  46853. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46854. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46855. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46856. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46857. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46858. var index = _this._keys.indexOf(evt.keyCode);
  46859. if (index === -1) {
  46860. _this._keys.push(evt.keyCode);
  46861. }
  46862. if (evt.preventDefault) {
  46863. if (!noPreventDefault) {
  46864. evt.preventDefault();
  46865. }
  46866. }
  46867. }
  46868. }
  46869. else {
  46870. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46871. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46872. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46873. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46874. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46875. var index = _this._keys.indexOf(evt.keyCode);
  46876. if (index >= 0) {
  46877. _this._keys.splice(index, 1);
  46878. }
  46879. if (evt.preventDefault) {
  46880. if (!noPreventDefault) {
  46881. evt.preventDefault();
  46882. }
  46883. }
  46884. }
  46885. }
  46886. });
  46887. };
  46888. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46889. if (this._scene) {
  46890. if (this._onKeyboardObserver) {
  46891. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46892. }
  46893. if (this._onCanvasBlurObserver) {
  46894. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46895. }
  46896. this._onKeyboardObserver = null;
  46897. this._onCanvasBlurObserver = null;
  46898. }
  46899. this._keys = [];
  46900. };
  46901. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46902. if (this._onKeyboardObserver) {
  46903. var camera = this.camera;
  46904. for (var index = 0; index < this._keys.length; index++) {
  46905. var keyCode = this._keys[index];
  46906. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46907. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46908. camera.inertialPanningX -= 1 / this.panningSensibility;
  46909. }
  46910. else {
  46911. camera.inertialAlphaOffset -= 0.01;
  46912. }
  46913. }
  46914. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46915. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46916. camera.inertialPanningY += 1 / this.panningSensibility;
  46917. }
  46918. else if (this._altPressed && this.useAltToZoom) {
  46919. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46920. }
  46921. else {
  46922. camera.inertialBetaOffset -= 0.01;
  46923. }
  46924. }
  46925. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46926. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46927. camera.inertialPanningX += 1 / this.panningSensibility;
  46928. }
  46929. else {
  46930. camera.inertialAlphaOffset += 0.01;
  46931. }
  46932. }
  46933. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46934. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46935. camera.inertialPanningY -= 1 / this.panningSensibility;
  46936. }
  46937. else if (this._altPressed && this.useAltToZoom) {
  46938. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46939. }
  46940. else {
  46941. camera.inertialBetaOffset += 0.01;
  46942. }
  46943. }
  46944. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46945. camera.restoreState();
  46946. }
  46947. }
  46948. }
  46949. };
  46950. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46951. return "ArcRotateCameraKeyboardMoveInput";
  46952. };
  46953. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46954. return "keyboard";
  46955. };
  46956. __decorate([
  46957. BABYLON.serialize()
  46958. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46959. __decorate([
  46960. BABYLON.serialize()
  46961. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46962. __decorate([
  46963. BABYLON.serialize()
  46964. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46965. __decorate([
  46966. BABYLON.serialize()
  46967. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46968. __decorate([
  46969. BABYLON.serialize()
  46970. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46971. __decorate([
  46972. BABYLON.serialize()
  46973. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46974. __decorate([
  46975. BABYLON.serialize()
  46976. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46977. __decorate([
  46978. BABYLON.serialize()
  46979. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46980. return ArcRotateCameraKeyboardMoveInput;
  46981. }());
  46982. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46983. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46984. })(BABYLON || (BABYLON = {}));
  46985. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46986. var BABYLON;
  46987. (function (BABYLON) {
  46988. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46989. function ArcRotateCameraMouseWheelInput() {
  46990. this.wheelPrecision = 3.0;
  46991. /**
  46992. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46993. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46994. */
  46995. this.wheelDeltaPercentage = 0;
  46996. }
  46997. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46998. var _this = this;
  46999. this._wheel = function (p, s) {
  47000. //sanity check - this should be a PointerWheel event.
  47001. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47002. return;
  47003. var event = p.event;
  47004. var delta = 0;
  47005. if (event.wheelDelta) {
  47006. if (_this.wheelDeltaPercentage) {
  47007. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47008. if (event.wheelDelta > 0) {
  47009. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47010. }
  47011. else {
  47012. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47013. }
  47014. }
  47015. else {
  47016. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47017. }
  47018. }
  47019. else if (event.detail) {
  47020. delta = -event.detail / _this.wheelPrecision;
  47021. }
  47022. if (delta)
  47023. _this.camera.inertialRadiusOffset += delta;
  47024. if (event.preventDefault) {
  47025. if (!noPreventDefault) {
  47026. event.preventDefault();
  47027. }
  47028. }
  47029. };
  47030. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47031. };
  47032. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47033. if (this._observer && element) {
  47034. this.camera.getScene().onPointerObservable.remove(this._observer);
  47035. this._observer = null;
  47036. this._wheel = null;
  47037. }
  47038. };
  47039. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47040. return "ArcRotateCameraMouseWheelInput";
  47041. };
  47042. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47043. return "mousewheel";
  47044. };
  47045. __decorate([
  47046. BABYLON.serialize()
  47047. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47048. __decorate([
  47049. BABYLON.serialize()
  47050. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47051. return ArcRotateCameraMouseWheelInput;
  47052. }());
  47053. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47054. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47055. })(BABYLON || (BABYLON = {}));
  47056. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47057. var BABYLON;
  47058. (function (BABYLON) {
  47059. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47060. function ArcRotateCameraPointersInput() {
  47061. this.buttons = [0, 1, 2];
  47062. this.angularSensibilityX = 1000.0;
  47063. this.angularSensibilityY = 1000.0;
  47064. this.pinchPrecision = 12.0;
  47065. /**
  47066. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47067. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47068. */
  47069. this.pinchDeltaPercentage = 0;
  47070. this.panningSensibility = 1000.0;
  47071. this.multiTouchPanning = true;
  47072. this.multiTouchPanAndZoom = true;
  47073. this._isPanClick = false;
  47074. this.pinchInwards = true;
  47075. }
  47076. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47077. var _this = this;
  47078. var engine = this.camera.getEngine();
  47079. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47080. var pointA = null;
  47081. var pointB = null;
  47082. var previousPinchSquaredDistance = 0;
  47083. var initialDistance = 0;
  47084. var twoFingerActivityCount = 0;
  47085. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47086. this._pointerInput = function (p, s) {
  47087. var evt = p.event;
  47088. var isTouch = p.event.pointerType === "touch";
  47089. if (engine.isInVRExclusivePointerMode) {
  47090. return;
  47091. }
  47092. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47093. return;
  47094. }
  47095. var srcElement = (evt.srcElement || evt.target);
  47096. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47097. try {
  47098. srcElement.setPointerCapture(evt.pointerId);
  47099. }
  47100. catch (e) {
  47101. //Nothing to do with the error. Execution will continue.
  47102. }
  47103. // Manage panning with pan button click
  47104. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47105. // manage pointers
  47106. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47107. if (pointA === null) {
  47108. pointA = cacheSoloPointer;
  47109. }
  47110. else if (pointB === null) {
  47111. pointB = cacheSoloPointer;
  47112. }
  47113. if (!noPreventDefault) {
  47114. evt.preventDefault();
  47115. element.focus();
  47116. }
  47117. }
  47118. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47119. _this.camera.restoreState();
  47120. }
  47121. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47122. try {
  47123. srcElement.releasePointerCapture(evt.pointerId);
  47124. }
  47125. catch (e) {
  47126. //Nothing to do with the error.
  47127. }
  47128. cacheSoloPointer = null;
  47129. previousPinchSquaredDistance = 0;
  47130. previousMultiTouchPanPosition.isPaning = false;
  47131. previousMultiTouchPanPosition.isPinching = false;
  47132. twoFingerActivityCount = 0;
  47133. initialDistance = 0;
  47134. if (!isTouch) {
  47135. pointB = null; // Mouse and pen are mono pointer
  47136. }
  47137. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47138. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47139. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47140. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47141. if (engine._badOS) {
  47142. pointA = pointB = null;
  47143. }
  47144. else {
  47145. //only remove the impacted pointer in case of multitouch allowing on most
  47146. //platforms switching from rotate to zoom and pan seamlessly.
  47147. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47148. pointA = pointB;
  47149. pointB = null;
  47150. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47151. }
  47152. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47153. pointB = null;
  47154. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47155. }
  47156. else {
  47157. pointA = pointB = null;
  47158. }
  47159. }
  47160. if (!noPreventDefault) {
  47161. evt.preventDefault();
  47162. }
  47163. }
  47164. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47165. if (!noPreventDefault) {
  47166. evt.preventDefault();
  47167. }
  47168. // One button down
  47169. if (pointA && pointB === null && cacheSoloPointer) {
  47170. if (_this.panningSensibility !== 0 &&
  47171. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47172. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47173. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47174. }
  47175. else {
  47176. var offsetX = evt.clientX - cacheSoloPointer.x;
  47177. var offsetY = evt.clientY - cacheSoloPointer.y;
  47178. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47179. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47180. }
  47181. cacheSoloPointer.x = evt.clientX;
  47182. cacheSoloPointer.y = evt.clientY;
  47183. }
  47184. // Two buttons down: pinch/pan
  47185. else if (pointA && pointB) {
  47186. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47187. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47188. ed.x = evt.clientX;
  47189. ed.y = evt.clientY;
  47190. var direction = _this.pinchInwards ? 1 : -1;
  47191. var distX = pointA.x - pointB.x;
  47192. var distY = pointA.y - pointB.y;
  47193. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47194. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47195. if (previousPinchSquaredDistance === 0) {
  47196. initialDistance = pinchDistance;
  47197. previousPinchSquaredDistance = pinchSquaredDistance;
  47198. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47199. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47200. return;
  47201. }
  47202. if (_this.multiTouchPanAndZoom) {
  47203. if (_this.pinchDeltaPercentage) {
  47204. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47205. }
  47206. else {
  47207. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47208. (_this.pinchPrecision *
  47209. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47210. direction);
  47211. }
  47212. if (_this.panningSensibility !== 0) {
  47213. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47214. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47215. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47216. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47217. previousMultiTouchPanPosition.x = pointersCenterX;
  47218. previousMultiTouchPanPosition.y = pointersCenterY;
  47219. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47220. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47221. }
  47222. }
  47223. else {
  47224. twoFingerActivityCount++;
  47225. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47226. if (_this.pinchDeltaPercentage) {
  47227. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47228. }
  47229. else {
  47230. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47231. (_this.pinchPrecision *
  47232. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47233. direction);
  47234. }
  47235. previousMultiTouchPanPosition.isPaning = false;
  47236. previousMultiTouchPanPosition.isPinching = true;
  47237. }
  47238. else {
  47239. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47240. if (!previousMultiTouchPanPosition.isPaning) {
  47241. previousMultiTouchPanPosition.isPaning = true;
  47242. previousMultiTouchPanPosition.isPinching = false;
  47243. previousMultiTouchPanPosition.x = ed.x;
  47244. previousMultiTouchPanPosition.y = ed.y;
  47245. return;
  47246. }
  47247. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47248. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47249. }
  47250. }
  47251. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47252. previousMultiTouchPanPosition.x = ed.x;
  47253. previousMultiTouchPanPosition.y = ed.y;
  47254. }
  47255. }
  47256. previousPinchSquaredDistance = pinchSquaredDistance;
  47257. }
  47258. }
  47259. };
  47260. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47261. this._onContextMenu = function (evt) {
  47262. evt.preventDefault();
  47263. };
  47264. if (!this.camera._useCtrlForPanning) {
  47265. element.addEventListener("contextmenu", this._onContextMenu, false);
  47266. }
  47267. this._onLostFocus = function () {
  47268. //this._keys = [];
  47269. pointA = pointB = null;
  47270. previousPinchSquaredDistance = 0;
  47271. previousMultiTouchPanPosition.isPaning = false;
  47272. previousMultiTouchPanPosition.isPinching = false;
  47273. twoFingerActivityCount = 0;
  47274. cacheSoloPointer = null;
  47275. initialDistance = 0;
  47276. };
  47277. this._onMouseMove = function (evt) {
  47278. if (!engine.isPointerLock) {
  47279. return;
  47280. }
  47281. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47282. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47283. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47284. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47285. if (!noPreventDefault) {
  47286. evt.preventDefault();
  47287. }
  47288. };
  47289. this._onGestureStart = function (e) {
  47290. if (window.MSGesture === undefined) {
  47291. return;
  47292. }
  47293. if (!_this._MSGestureHandler) {
  47294. _this._MSGestureHandler = new MSGesture();
  47295. _this._MSGestureHandler.target = element;
  47296. }
  47297. _this._MSGestureHandler.addPointer(e.pointerId);
  47298. };
  47299. this._onGesture = function (e) {
  47300. _this.camera.radius *= e.scale;
  47301. if (e.preventDefault) {
  47302. if (!noPreventDefault) {
  47303. e.stopPropagation();
  47304. e.preventDefault();
  47305. }
  47306. }
  47307. };
  47308. element.addEventListener("mousemove", this._onMouseMove, false);
  47309. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47310. element.addEventListener("MSGestureChange", this._onGesture, false);
  47311. BABYLON.Tools.RegisterTopRootEvents([
  47312. { name: "blur", handler: this._onLostFocus }
  47313. ]);
  47314. };
  47315. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47316. if (this._onLostFocus) {
  47317. BABYLON.Tools.UnregisterTopRootEvents([
  47318. { name: "blur", handler: this._onLostFocus }
  47319. ]);
  47320. }
  47321. if (element && this._observer) {
  47322. this.camera.getScene().onPointerObservable.remove(this._observer);
  47323. this._observer = null;
  47324. if (this._onContextMenu) {
  47325. element.removeEventListener("contextmenu", this._onContextMenu);
  47326. }
  47327. if (this._onMouseMove) {
  47328. element.removeEventListener("mousemove", this._onMouseMove);
  47329. }
  47330. if (this._onGestureStart) {
  47331. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47332. }
  47333. if (this._onGesture) {
  47334. element.removeEventListener("MSGestureChange", this._onGesture);
  47335. }
  47336. this._isPanClick = false;
  47337. this.pinchInwards = true;
  47338. this._onMouseMove = null;
  47339. this._onGestureStart = null;
  47340. this._onGesture = null;
  47341. this._MSGestureHandler = null;
  47342. this._onLostFocus = null;
  47343. this._onContextMenu = null;
  47344. }
  47345. };
  47346. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47347. return "ArcRotateCameraPointersInput";
  47348. };
  47349. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47350. return "pointers";
  47351. };
  47352. __decorate([
  47353. BABYLON.serialize()
  47354. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47355. __decorate([
  47356. BABYLON.serialize()
  47357. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47358. __decorate([
  47359. BABYLON.serialize()
  47360. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47361. __decorate([
  47362. BABYLON.serialize()
  47363. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47364. __decorate([
  47365. BABYLON.serialize()
  47366. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47367. __decorate([
  47368. BABYLON.serialize()
  47369. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47370. __decorate([
  47371. BABYLON.serialize()
  47372. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47373. __decorate([
  47374. BABYLON.serialize()
  47375. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47376. return ArcRotateCameraPointersInput;
  47377. }());
  47378. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47379. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47380. })(BABYLON || (BABYLON = {}));
  47381. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47382. var BABYLON;
  47383. (function (BABYLON) {
  47384. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47385. __extends(ArcRotateCameraInputsManager, _super);
  47386. function ArcRotateCameraInputsManager(camera) {
  47387. return _super.call(this, camera) || this;
  47388. }
  47389. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47390. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47391. return this;
  47392. };
  47393. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47394. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47395. return this;
  47396. };
  47397. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47398. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47399. return this;
  47400. };
  47401. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47402. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47403. return this;
  47404. };
  47405. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47406. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47407. return this;
  47408. };
  47409. return ArcRotateCameraInputsManager;
  47410. }(BABYLON.CameraInputsManager));
  47411. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47412. })(BABYLON || (BABYLON = {}));
  47413. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47414. var BABYLON;
  47415. (function (BABYLON) {
  47416. var ArcRotateCamera = /** @class */ (function (_super) {
  47417. __extends(ArcRotateCamera, _super);
  47418. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47419. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47420. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47421. _this.inertialAlphaOffset = 0;
  47422. _this.inertialBetaOffset = 0;
  47423. _this.inertialRadiusOffset = 0;
  47424. _this.lowerAlphaLimit = null;
  47425. _this.upperAlphaLimit = null;
  47426. _this.lowerBetaLimit = 0.01;
  47427. _this.upperBetaLimit = Math.PI;
  47428. _this.lowerRadiusLimit = null;
  47429. _this.upperRadiusLimit = null;
  47430. _this.inertialPanningX = 0;
  47431. _this.inertialPanningY = 0;
  47432. _this.pinchToPanMaxDistance = 20;
  47433. _this.panningDistanceLimit = null;
  47434. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47435. _this.panningInertia = 0.9;
  47436. //-- end properties for backward compatibility for inputs
  47437. _this.zoomOnFactor = 1;
  47438. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47439. _this.allowUpsideDown = true;
  47440. _this._viewMatrix = new BABYLON.Matrix();
  47441. // Panning
  47442. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47443. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47444. _this.checkCollisions = false;
  47445. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47446. _this._previousPosition = BABYLON.Vector3.Zero();
  47447. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47448. _this._newPosition = BABYLON.Vector3.Zero();
  47449. _this._computationVector = BABYLON.Vector3.Zero();
  47450. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47451. if (collidedMesh === void 0) { collidedMesh = null; }
  47452. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47453. newPosition.multiplyInPlace(_this._collider._radius);
  47454. }
  47455. if (!collidedMesh) {
  47456. _this._previousPosition.copyFrom(_this.position);
  47457. }
  47458. else {
  47459. _this.setPosition(newPosition);
  47460. if (_this.onCollide) {
  47461. _this.onCollide(collidedMesh);
  47462. }
  47463. }
  47464. // Recompute because of constraints
  47465. var cosa = Math.cos(_this.alpha);
  47466. var sina = Math.sin(_this.alpha);
  47467. var cosb = Math.cos(_this.beta);
  47468. var sinb = Math.sin(_this.beta);
  47469. if (sinb === 0) {
  47470. sinb = 0.0001;
  47471. }
  47472. var target = _this._getTargetPosition();
  47473. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47474. target.addToRef(_this._computationVector, _this._newPosition);
  47475. _this.position.copyFrom(_this._newPosition);
  47476. var up = _this.upVector;
  47477. if (_this.allowUpsideDown && _this.beta < 0) {
  47478. up = up.clone();
  47479. up = up.negate();
  47480. }
  47481. _this._computeViewMatrix(_this.position, target, up);
  47482. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47483. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47484. _this._collisionTriggered = false;
  47485. };
  47486. _this._target = BABYLON.Vector3.Zero();
  47487. if (target) {
  47488. _this.setTarget(target);
  47489. }
  47490. _this.alpha = alpha;
  47491. _this.beta = beta;
  47492. _this.radius = radius;
  47493. _this.getViewMatrix();
  47494. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47495. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47496. return _this;
  47497. }
  47498. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47499. get: function () {
  47500. return this._target;
  47501. },
  47502. set: function (value) {
  47503. this.setTarget(value);
  47504. },
  47505. enumerable: true,
  47506. configurable: true
  47507. });
  47508. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47509. //-- begin properties for backward compatibility for inputs
  47510. get: function () {
  47511. var pointers = this.inputs.attached["pointers"];
  47512. if (pointers)
  47513. return pointers.angularSensibilityX;
  47514. return 0;
  47515. },
  47516. set: function (value) {
  47517. var pointers = this.inputs.attached["pointers"];
  47518. if (pointers) {
  47519. pointers.angularSensibilityX = value;
  47520. }
  47521. },
  47522. enumerable: true,
  47523. configurable: true
  47524. });
  47525. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47526. get: function () {
  47527. var pointers = this.inputs.attached["pointers"];
  47528. if (pointers)
  47529. return pointers.angularSensibilityY;
  47530. return 0;
  47531. },
  47532. set: function (value) {
  47533. var pointers = this.inputs.attached["pointers"];
  47534. if (pointers) {
  47535. pointers.angularSensibilityY = value;
  47536. }
  47537. },
  47538. enumerable: true,
  47539. configurable: true
  47540. });
  47541. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47542. get: function () {
  47543. var pointers = this.inputs.attached["pointers"];
  47544. if (pointers)
  47545. return pointers.pinchPrecision;
  47546. return 0;
  47547. },
  47548. set: function (value) {
  47549. var pointers = this.inputs.attached["pointers"];
  47550. if (pointers) {
  47551. pointers.pinchPrecision = value;
  47552. }
  47553. },
  47554. enumerable: true,
  47555. configurable: true
  47556. });
  47557. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47558. get: function () {
  47559. var pointers = this.inputs.attached["pointers"];
  47560. if (pointers)
  47561. return pointers.pinchDeltaPercentage;
  47562. return 0;
  47563. },
  47564. set: function (value) {
  47565. var pointers = this.inputs.attached["pointers"];
  47566. if (pointers) {
  47567. pointers.pinchDeltaPercentage = value;
  47568. }
  47569. },
  47570. enumerable: true,
  47571. configurable: true
  47572. });
  47573. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47574. get: function () {
  47575. var pointers = this.inputs.attached["pointers"];
  47576. if (pointers)
  47577. return pointers.panningSensibility;
  47578. return 0;
  47579. },
  47580. set: function (value) {
  47581. var pointers = this.inputs.attached["pointers"];
  47582. if (pointers) {
  47583. pointers.panningSensibility = value;
  47584. }
  47585. },
  47586. enumerable: true,
  47587. configurable: true
  47588. });
  47589. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47590. get: function () {
  47591. var keyboard = this.inputs.attached["keyboard"];
  47592. if (keyboard)
  47593. return keyboard.keysUp;
  47594. return [];
  47595. },
  47596. set: function (value) {
  47597. var keyboard = this.inputs.attached["keyboard"];
  47598. if (keyboard)
  47599. keyboard.keysUp = value;
  47600. },
  47601. enumerable: true,
  47602. configurable: true
  47603. });
  47604. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47605. get: function () {
  47606. var keyboard = this.inputs.attached["keyboard"];
  47607. if (keyboard)
  47608. return keyboard.keysDown;
  47609. return [];
  47610. },
  47611. set: function (value) {
  47612. var keyboard = this.inputs.attached["keyboard"];
  47613. if (keyboard)
  47614. keyboard.keysDown = value;
  47615. },
  47616. enumerable: true,
  47617. configurable: true
  47618. });
  47619. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47620. get: function () {
  47621. var keyboard = this.inputs.attached["keyboard"];
  47622. if (keyboard)
  47623. return keyboard.keysLeft;
  47624. return [];
  47625. },
  47626. set: function (value) {
  47627. var keyboard = this.inputs.attached["keyboard"];
  47628. if (keyboard)
  47629. keyboard.keysLeft = value;
  47630. },
  47631. enumerable: true,
  47632. configurable: true
  47633. });
  47634. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47635. get: function () {
  47636. var keyboard = this.inputs.attached["keyboard"];
  47637. if (keyboard)
  47638. return keyboard.keysRight;
  47639. return [];
  47640. },
  47641. set: function (value) {
  47642. var keyboard = this.inputs.attached["keyboard"];
  47643. if (keyboard)
  47644. keyboard.keysRight = value;
  47645. },
  47646. enumerable: true,
  47647. configurable: true
  47648. });
  47649. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47650. get: function () {
  47651. var mousewheel = this.inputs.attached["mousewheel"];
  47652. if (mousewheel)
  47653. return mousewheel.wheelPrecision;
  47654. return 0;
  47655. },
  47656. set: function (value) {
  47657. var mousewheel = this.inputs.attached["mousewheel"];
  47658. if (mousewheel)
  47659. mousewheel.wheelPrecision = value;
  47660. },
  47661. enumerable: true,
  47662. configurable: true
  47663. });
  47664. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47665. get: function () {
  47666. var mousewheel = this.inputs.attached["mousewheel"];
  47667. if (mousewheel)
  47668. return mousewheel.wheelDeltaPercentage;
  47669. return 0;
  47670. },
  47671. set: function (value) {
  47672. var mousewheel = this.inputs.attached["mousewheel"];
  47673. if (mousewheel)
  47674. mousewheel.wheelDeltaPercentage = value;
  47675. },
  47676. enumerable: true,
  47677. configurable: true
  47678. });
  47679. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47680. get: function () {
  47681. return this._bouncingBehavior;
  47682. },
  47683. enumerable: true,
  47684. configurable: true
  47685. });
  47686. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47687. get: function () {
  47688. return this._bouncingBehavior != null;
  47689. },
  47690. set: function (value) {
  47691. if (value === this.useBouncingBehavior) {
  47692. return;
  47693. }
  47694. if (value) {
  47695. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47696. this.addBehavior(this._bouncingBehavior);
  47697. }
  47698. else if (this._bouncingBehavior) {
  47699. this.removeBehavior(this._bouncingBehavior);
  47700. this._bouncingBehavior = null;
  47701. }
  47702. },
  47703. enumerable: true,
  47704. configurable: true
  47705. });
  47706. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47707. get: function () {
  47708. return this._framingBehavior;
  47709. },
  47710. enumerable: true,
  47711. configurable: true
  47712. });
  47713. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47714. get: function () {
  47715. return this._framingBehavior != null;
  47716. },
  47717. set: function (value) {
  47718. if (value === this.useFramingBehavior) {
  47719. return;
  47720. }
  47721. if (value) {
  47722. this._framingBehavior = new BABYLON.FramingBehavior();
  47723. this.addBehavior(this._framingBehavior);
  47724. }
  47725. else if (this._framingBehavior) {
  47726. this.removeBehavior(this._framingBehavior);
  47727. this._framingBehavior = null;
  47728. }
  47729. },
  47730. enumerable: true,
  47731. configurable: true
  47732. });
  47733. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47734. get: function () {
  47735. return this._autoRotationBehavior;
  47736. },
  47737. enumerable: true,
  47738. configurable: true
  47739. });
  47740. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47741. get: function () {
  47742. return this._autoRotationBehavior != null;
  47743. },
  47744. set: function (value) {
  47745. if (value === this.useAutoRotationBehavior) {
  47746. return;
  47747. }
  47748. if (value) {
  47749. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47750. this.addBehavior(this._autoRotationBehavior);
  47751. }
  47752. else if (this._autoRotationBehavior) {
  47753. this.removeBehavior(this._autoRotationBehavior);
  47754. this._autoRotationBehavior = null;
  47755. }
  47756. },
  47757. enumerable: true,
  47758. configurable: true
  47759. });
  47760. // Cache
  47761. ArcRotateCamera.prototype._initCache = function () {
  47762. _super.prototype._initCache.call(this);
  47763. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47764. this._cache.alpha = undefined;
  47765. this._cache.beta = undefined;
  47766. this._cache.radius = undefined;
  47767. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47768. };
  47769. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47770. if (!ignoreParentClass) {
  47771. _super.prototype._updateCache.call(this);
  47772. }
  47773. this._cache._target.copyFrom(this._getTargetPosition());
  47774. this._cache.alpha = this.alpha;
  47775. this._cache.beta = this.beta;
  47776. this._cache.radius = this.radius;
  47777. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47778. };
  47779. ArcRotateCamera.prototype._getTargetPosition = function () {
  47780. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47781. var pos = this._targetHost.getAbsolutePosition();
  47782. if (this._targetBoundingCenter) {
  47783. pos.addToRef(this._targetBoundingCenter, this._target);
  47784. }
  47785. else {
  47786. this._target.copyFrom(pos);
  47787. }
  47788. }
  47789. var lockedTargetPosition = this._getLockedTargetPosition();
  47790. if (lockedTargetPosition) {
  47791. return lockedTargetPosition;
  47792. }
  47793. return this._target;
  47794. };
  47795. ArcRotateCamera.prototype.storeState = function () {
  47796. this._storedAlpha = this.alpha;
  47797. this._storedBeta = this.beta;
  47798. this._storedRadius = this.radius;
  47799. this._storedTarget = this._getTargetPosition().clone();
  47800. return _super.prototype.storeState.call(this);
  47801. };
  47802. /**
  47803. * Restored camera state. You must call storeState() first
  47804. */
  47805. ArcRotateCamera.prototype._restoreStateValues = function () {
  47806. if (!_super.prototype._restoreStateValues.call(this)) {
  47807. return false;
  47808. }
  47809. this.alpha = this._storedAlpha;
  47810. this.beta = this._storedBeta;
  47811. this.radius = this._storedRadius;
  47812. this.setTarget(this._storedTarget.clone());
  47813. this.inertialAlphaOffset = 0;
  47814. this.inertialBetaOffset = 0;
  47815. this.inertialRadiusOffset = 0;
  47816. this.inertialPanningX = 0;
  47817. this.inertialPanningY = 0;
  47818. return true;
  47819. };
  47820. // Synchronized
  47821. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47822. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47823. return false;
  47824. return this._cache._target.equals(this._getTargetPosition())
  47825. && this._cache.alpha === this.alpha
  47826. && this._cache.beta === this.beta
  47827. && this._cache.radius === this.radius
  47828. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47829. };
  47830. // Methods
  47831. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47832. var _this = this;
  47833. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47834. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47835. this._useCtrlForPanning = useCtrlForPanning;
  47836. this._panningMouseButton = panningMouseButton;
  47837. this.inputs.attachElement(element, noPreventDefault);
  47838. this._reset = function () {
  47839. _this.inertialAlphaOffset = 0;
  47840. _this.inertialBetaOffset = 0;
  47841. _this.inertialRadiusOffset = 0;
  47842. _this.inertialPanningX = 0;
  47843. _this.inertialPanningY = 0;
  47844. };
  47845. };
  47846. ArcRotateCamera.prototype.detachControl = function (element) {
  47847. this.inputs.detachElement(element);
  47848. if (this._reset) {
  47849. this._reset();
  47850. }
  47851. };
  47852. ArcRotateCamera.prototype._checkInputs = function () {
  47853. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47854. if (this._collisionTriggered) {
  47855. return;
  47856. }
  47857. this.inputs.checkInputs();
  47858. // Inertia
  47859. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47860. var inertialAlphaOffset = this.inertialAlphaOffset;
  47861. if (this.beta <= 0)
  47862. inertialAlphaOffset *= -1;
  47863. if (this.getScene().useRightHandedSystem)
  47864. inertialAlphaOffset *= -1;
  47865. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47866. inertialAlphaOffset *= -1;
  47867. this.alpha += inertialAlphaOffset;
  47868. this.beta += this.inertialBetaOffset;
  47869. this.radius -= this.inertialRadiusOffset;
  47870. this.inertialAlphaOffset *= this.inertia;
  47871. this.inertialBetaOffset *= this.inertia;
  47872. this.inertialRadiusOffset *= this.inertia;
  47873. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47874. this.inertialAlphaOffset = 0;
  47875. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47876. this.inertialBetaOffset = 0;
  47877. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47878. this.inertialRadiusOffset = 0;
  47879. }
  47880. // Panning inertia
  47881. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47882. if (!this._localDirection) {
  47883. this._localDirection = BABYLON.Vector3.Zero();
  47884. this._transformedDirection = BABYLON.Vector3.Zero();
  47885. }
  47886. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47887. this._localDirection.multiplyInPlace(this.panningAxis);
  47888. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47889. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47890. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47891. if (!this.panningAxis.y) {
  47892. this._transformedDirection.y = 0;
  47893. }
  47894. if (!this._targetHost) {
  47895. if (this.panningDistanceLimit) {
  47896. this._transformedDirection.addInPlace(this._target);
  47897. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47898. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47899. this._target.copyFrom(this._transformedDirection);
  47900. }
  47901. }
  47902. else {
  47903. this._target.addInPlace(this._transformedDirection);
  47904. }
  47905. }
  47906. this.inertialPanningX *= this.panningInertia;
  47907. this.inertialPanningY *= this.panningInertia;
  47908. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47909. this.inertialPanningX = 0;
  47910. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47911. this.inertialPanningY = 0;
  47912. }
  47913. // Limits
  47914. this._checkLimits();
  47915. _super.prototype._checkInputs.call(this);
  47916. };
  47917. ArcRotateCamera.prototype._checkLimits = function () {
  47918. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47919. if (this.allowUpsideDown && this.beta > Math.PI) {
  47920. this.beta = this.beta - (2 * Math.PI);
  47921. }
  47922. }
  47923. else {
  47924. if (this.beta < this.lowerBetaLimit) {
  47925. this.beta = this.lowerBetaLimit;
  47926. }
  47927. }
  47928. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47929. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47930. this.beta = this.beta + (2 * Math.PI);
  47931. }
  47932. }
  47933. else {
  47934. if (this.beta > this.upperBetaLimit) {
  47935. this.beta = this.upperBetaLimit;
  47936. }
  47937. }
  47938. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47939. this.alpha = this.lowerAlphaLimit;
  47940. }
  47941. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47942. this.alpha = this.upperAlphaLimit;
  47943. }
  47944. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47945. this.radius = this.lowerRadiusLimit;
  47946. }
  47947. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47948. this.radius = this.upperRadiusLimit;
  47949. }
  47950. };
  47951. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47952. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47953. this.radius = this._computationVector.length();
  47954. if (this.radius === 0) {
  47955. this.radius = 0.0001; // Just to avoid division by zero
  47956. }
  47957. // Alpha
  47958. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47959. if (this._computationVector.z < 0) {
  47960. this.alpha = 2 * Math.PI - this.alpha;
  47961. }
  47962. // Beta
  47963. this.beta = Math.acos(this._computationVector.y / this.radius);
  47964. this._checkLimits();
  47965. };
  47966. ArcRotateCamera.prototype.setPosition = function (position) {
  47967. if (this.position.equals(position)) {
  47968. return;
  47969. }
  47970. this.position.copyFrom(position);
  47971. this.rebuildAnglesAndRadius();
  47972. };
  47973. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47974. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47975. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47976. if (target.getBoundingInfo) {
  47977. if (toBoundingCenter) {
  47978. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47979. }
  47980. else {
  47981. this._targetBoundingCenter = null;
  47982. }
  47983. this._targetHost = target;
  47984. this._target = this._getTargetPosition();
  47985. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47986. }
  47987. else {
  47988. var newTarget = target;
  47989. var currentTarget = this._getTargetPosition();
  47990. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47991. return;
  47992. }
  47993. this._targetHost = null;
  47994. this._target = newTarget;
  47995. this._targetBoundingCenter = null;
  47996. this.onMeshTargetChangedObservable.notifyObservers(null);
  47997. }
  47998. this.rebuildAnglesAndRadius();
  47999. };
  48000. ArcRotateCamera.prototype._getViewMatrix = function () {
  48001. // Compute
  48002. var cosa = Math.cos(this.alpha);
  48003. var sina = Math.sin(this.alpha);
  48004. var cosb = Math.cos(this.beta);
  48005. var sinb = Math.sin(this.beta);
  48006. if (sinb === 0) {
  48007. sinb = 0.0001;
  48008. }
  48009. var target = this._getTargetPosition();
  48010. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48011. target.addToRef(this._computationVector, this._newPosition);
  48012. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48013. if (!this._collider) {
  48014. this._collider = new BABYLON.Collider();
  48015. }
  48016. this._collider._radius = this.collisionRadius;
  48017. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48018. this._collisionTriggered = true;
  48019. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48020. }
  48021. else {
  48022. this.position.copyFrom(this._newPosition);
  48023. var up = this.upVector;
  48024. if (this.allowUpsideDown && sinb < 0) {
  48025. up = up.clone();
  48026. up = up.negate();
  48027. }
  48028. this._computeViewMatrix(this.position, target, up);
  48029. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48030. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48031. }
  48032. this._currentTarget = target;
  48033. return this._viewMatrix;
  48034. };
  48035. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48036. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48037. meshes = meshes || this.getScene().meshes;
  48038. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48039. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48040. this.radius = distance * this.zoomOnFactor;
  48041. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48042. };
  48043. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48044. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48045. var meshesOrMinMaxVector;
  48046. var distance;
  48047. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48048. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48049. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48050. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48051. }
  48052. else { //minMaxVector and distance
  48053. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48054. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48055. distance = minMaxVectorAndDistance.distance;
  48056. }
  48057. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48058. if (!doNotUpdateMaxZ) {
  48059. this.maxZ = distance * 2;
  48060. }
  48061. };
  48062. /**
  48063. * @override
  48064. * Override Camera.createRigCamera
  48065. */
  48066. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48067. var alphaShift = 0;
  48068. switch (this.cameraRigMode) {
  48069. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48070. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48071. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48072. case BABYLON.Camera.RIG_MODE_VR:
  48073. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48074. break;
  48075. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48076. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48077. break;
  48078. }
  48079. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48080. rigCam._cameraRigParams = {};
  48081. return rigCam;
  48082. };
  48083. /**
  48084. * @override
  48085. * Override Camera._updateRigCameras
  48086. */
  48087. ArcRotateCamera.prototype._updateRigCameras = function () {
  48088. var camLeft = this._rigCameras[0];
  48089. var camRight = this._rigCameras[1];
  48090. camLeft.beta = camRight.beta = this.beta;
  48091. camLeft.radius = camRight.radius = this.radius;
  48092. switch (this.cameraRigMode) {
  48093. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48094. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48095. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48096. case BABYLON.Camera.RIG_MODE_VR:
  48097. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48098. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48099. break;
  48100. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48101. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48102. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48103. break;
  48104. }
  48105. _super.prototype._updateRigCameras.call(this);
  48106. };
  48107. ArcRotateCamera.prototype.dispose = function () {
  48108. this.inputs.clear();
  48109. _super.prototype.dispose.call(this);
  48110. };
  48111. ArcRotateCamera.prototype.getClassName = function () {
  48112. return "ArcRotateCamera";
  48113. };
  48114. __decorate([
  48115. BABYLON.serialize()
  48116. ], ArcRotateCamera.prototype, "alpha", void 0);
  48117. __decorate([
  48118. BABYLON.serialize()
  48119. ], ArcRotateCamera.prototype, "beta", void 0);
  48120. __decorate([
  48121. BABYLON.serialize()
  48122. ], ArcRotateCamera.prototype, "radius", void 0);
  48123. __decorate([
  48124. BABYLON.serializeAsVector3("target")
  48125. ], ArcRotateCamera.prototype, "_target", void 0);
  48126. __decorate([
  48127. BABYLON.serialize()
  48128. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48129. __decorate([
  48130. BABYLON.serialize()
  48131. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48132. __decorate([
  48133. BABYLON.serialize()
  48134. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48135. __decorate([
  48136. BABYLON.serialize()
  48137. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48138. __decorate([
  48139. BABYLON.serialize()
  48140. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48141. __decorate([
  48142. BABYLON.serialize()
  48143. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48144. __decorate([
  48145. BABYLON.serialize()
  48146. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48147. __decorate([
  48148. BABYLON.serialize()
  48149. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48150. __decorate([
  48151. BABYLON.serialize()
  48152. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48153. __decorate([
  48154. BABYLON.serialize()
  48155. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48156. __decorate([
  48157. BABYLON.serialize()
  48158. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48159. __decorate([
  48160. BABYLON.serialize()
  48161. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48162. __decorate([
  48163. BABYLON.serialize()
  48164. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48165. __decorate([
  48166. BABYLON.serializeAsVector3()
  48167. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48168. __decorate([
  48169. BABYLON.serialize()
  48170. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48171. __decorate([
  48172. BABYLON.serialize()
  48173. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48174. __decorate([
  48175. BABYLON.serialize()
  48176. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48177. return ArcRotateCamera;
  48178. }(BABYLON.TargetCamera));
  48179. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48180. })(BABYLON || (BABYLON = {}));
  48181. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48182. var BABYLON;
  48183. (function (BABYLON) {
  48184. /**
  48185. * The HemisphericLight simulates the ambient environment light,
  48186. * so the passed direction is the light reflection direction, not the incoming direction.
  48187. */
  48188. var HemisphericLight = /** @class */ (function (_super) {
  48189. __extends(HemisphericLight, _super);
  48190. /**
  48191. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48192. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48193. * The HemisphericLight can't cast shadows.
  48194. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48195. * @param name The friendly name of the light
  48196. * @param direction The direction of the light reflection
  48197. * @param scene The scene the light belongs to
  48198. */
  48199. function HemisphericLight(name, direction, scene) {
  48200. var _this = _super.call(this, name, scene) || this;
  48201. /**
  48202. * The groundColor is the light in the opposite direction to the one specified during creation.
  48203. * 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.
  48204. */
  48205. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48206. _this.direction = direction || BABYLON.Vector3.Up();
  48207. return _this;
  48208. }
  48209. HemisphericLight.prototype._buildUniformLayout = function () {
  48210. this._uniformBuffer.addUniform("vLightData", 4);
  48211. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48212. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48213. this._uniformBuffer.addUniform("vLightGround", 3);
  48214. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48215. this._uniformBuffer.addUniform("depthValues", 2);
  48216. this._uniformBuffer.create();
  48217. };
  48218. /**
  48219. * Returns the string "HemisphericLight".
  48220. * @return The class name
  48221. */
  48222. HemisphericLight.prototype.getClassName = function () {
  48223. return "HemisphericLight";
  48224. };
  48225. /**
  48226. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48227. * Returns the updated direction.
  48228. * @param target The target the direction should point to
  48229. * @return The computed direction
  48230. */
  48231. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48232. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48233. return this.direction;
  48234. };
  48235. /**
  48236. * Returns the shadow generator associated to the light.
  48237. * @returns Always null for hemispheric lights because it does not support shadows.
  48238. */
  48239. HemisphericLight.prototype.getShadowGenerator = function () {
  48240. return null;
  48241. };
  48242. /**
  48243. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48244. * @param effect The effect to update
  48245. * @param lightIndex The index of the light in the effect to update
  48246. * @returns The hemispheric light
  48247. */
  48248. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48249. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48250. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48251. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48252. return this;
  48253. };
  48254. /**
  48255. * @hidden internal use only.
  48256. */
  48257. HemisphericLight.prototype._getWorldMatrix = function () {
  48258. if (!this._worldMatrix) {
  48259. this._worldMatrix = BABYLON.Matrix.Identity();
  48260. }
  48261. return this._worldMatrix;
  48262. };
  48263. /**
  48264. * Returns the integer 3.
  48265. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48266. */
  48267. HemisphericLight.prototype.getTypeID = function () {
  48268. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48269. };
  48270. __decorate([
  48271. BABYLON.serializeAsColor3()
  48272. ], HemisphericLight.prototype, "groundColor", void 0);
  48273. __decorate([
  48274. BABYLON.serializeAsVector3()
  48275. ], HemisphericLight.prototype, "direction", void 0);
  48276. return HemisphericLight;
  48277. }(BABYLON.Light));
  48278. BABYLON.HemisphericLight = HemisphericLight;
  48279. })(BABYLON || (BABYLON = {}));
  48280. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48281. var BABYLON;
  48282. (function (BABYLON) {
  48283. /**
  48284. * Base implementation IShadowLight
  48285. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48286. */
  48287. var ShadowLight = /** @class */ (function (_super) {
  48288. __extends(ShadowLight, _super);
  48289. function ShadowLight() {
  48290. var _this = _super !== null && _super.apply(this, arguments) || this;
  48291. _this._needProjectionMatrixCompute = true;
  48292. return _this;
  48293. }
  48294. ShadowLight.prototype._setPosition = function (value) {
  48295. this._position = value;
  48296. };
  48297. Object.defineProperty(ShadowLight.prototype, "position", {
  48298. /**
  48299. * Sets the position the shadow will be casted from. Also use as the light position for both
  48300. * point and spot lights.
  48301. */
  48302. get: function () {
  48303. return this._position;
  48304. },
  48305. /**
  48306. * Sets the position the shadow will be casted from. Also use as the light position for both
  48307. * point and spot lights.
  48308. */
  48309. set: function (value) {
  48310. this._setPosition(value);
  48311. },
  48312. enumerable: true,
  48313. configurable: true
  48314. });
  48315. ShadowLight.prototype._setDirection = function (value) {
  48316. this._direction = value;
  48317. };
  48318. Object.defineProperty(ShadowLight.prototype, "direction", {
  48319. /**
  48320. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48321. * Also use as the light direction on spot and directional lights.
  48322. */
  48323. get: function () {
  48324. return this._direction;
  48325. },
  48326. /**
  48327. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48328. * Also use as the light direction on spot and directional lights.
  48329. */
  48330. set: function (value) {
  48331. this._setDirection(value);
  48332. },
  48333. enumerable: true,
  48334. configurable: true
  48335. });
  48336. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48337. /**
  48338. * Gets the shadow projection clipping minimum z value.
  48339. */
  48340. get: function () {
  48341. return this._shadowMinZ;
  48342. },
  48343. /**
  48344. * Sets the shadow projection clipping minimum z value.
  48345. */
  48346. set: function (value) {
  48347. this._shadowMinZ = value;
  48348. this.forceProjectionMatrixCompute();
  48349. },
  48350. enumerable: true,
  48351. configurable: true
  48352. });
  48353. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48354. /**
  48355. * Sets the shadow projection clipping maximum z value.
  48356. */
  48357. get: function () {
  48358. return this._shadowMaxZ;
  48359. },
  48360. /**
  48361. * Gets the shadow projection clipping maximum z value.
  48362. */
  48363. set: function (value) {
  48364. this._shadowMaxZ = value;
  48365. this.forceProjectionMatrixCompute();
  48366. },
  48367. enumerable: true,
  48368. configurable: true
  48369. });
  48370. /**
  48371. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48372. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48373. */
  48374. ShadowLight.prototype.computeTransformedInformation = function () {
  48375. if (this.parent && this.parent.getWorldMatrix) {
  48376. if (!this.transformedPosition) {
  48377. this.transformedPosition = BABYLON.Vector3.Zero();
  48378. }
  48379. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48380. // In case the direction is present.
  48381. if (this.direction) {
  48382. if (!this.transformedDirection) {
  48383. this.transformedDirection = BABYLON.Vector3.Zero();
  48384. }
  48385. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48386. }
  48387. return true;
  48388. }
  48389. return false;
  48390. };
  48391. /**
  48392. * Return the depth scale used for the shadow map.
  48393. * @returns the depth scale.
  48394. */
  48395. ShadowLight.prototype.getDepthScale = function () {
  48396. return 50.0;
  48397. };
  48398. /**
  48399. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48400. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48401. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48402. */
  48403. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48404. return this.transformedDirection ? this.transformedDirection : this.direction;
  48405. };
  48406. /**
  48407. * Returns the ShadowLight absolute position in the World.
  48408. * @returns the position vector in world space
  48409. */
  48410. ShadowLight.prototype.getAbsolutePosition = function () {
  48411. return this.transformedPosition ? this.transformedPosition : this.position;
  48412. };
  48413. /**
  48414. * Sets the ShadowLight direction toward the passed target.
  48415. * @param target The point tot target in local space
  48416. * @returns the updated ShadowLight direction
  48417. */
  48418. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48419. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48420. return this.direction;
  48421. };
  48422. /**
  48423. * Returns the light rotation in euler definition.
  48424. * @returns the x y z rotation in local space.
  48425. */
  48426. ShadowLight.prototype.getRotation = function () {
  48427. this.direction.normalize();
  48428. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48429. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48430. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48431. };
  48432. /**
  48433. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48434. * @returns true if a cube texture needs to be use
  48435. */
  48436. ShadowLight.prototype.needCube = function () {
  48437. return false;
  48438. };
  48439. /**
  48440. * Detects if the projection matrix requires to be recomputed this frame.
  48441. * @returns true if it requires to be recomputed otherwise, false.
  48442. */
  48443. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48444. return this._needProjectionMatrixCompute;
  48445. };
  48446. /**
  48447. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48448. */
  48449. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48450. this._needProjectionMatrixCompute = true;
  48451. };
  48452. /**
  48453. * Get the world matrix of the sahdow lights.
  48454. * @hidden Internal Use Only
  48455. */
  48456. ShadowLight.prototype._getWorldMatrix = function () {
  48457. if (!this._worldMatrix) {
  48458. this._worldMatrix = BABYLON.Matrix.Identity();
  48459. }
  48460. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48461. return this._worldMatrix;
  48462. };
  48463. /**
  48464. * Gets the minZ used for shadow according to both the scene and the light.
  48465. * @param activeCamera The camera we are returning the min for
  48466. * @returns the depth min z
  48467. */
  48468. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48469. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48470. };
  48471. /**
  48472. * Gets the maxZ used for shadow according to both the scene and the light.
  48473. * @param activeCamera The camera we are returning the max for
  48474. * @returns the depth max z
  48475. */
  48476. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48477. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48478. };
  48479. /**
  48480. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48481. * @param matrix The materix to updated with the projection information
  48482. * @param viewMatrix The transform matrix of the light
  48483. * @param renderList The list of mesh to render in the map
  48484. * @returns The current light
  48485. */
  48486. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48487. if (this.customProjectionMatrixBuilder) {
  48488. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48489. }
  48490. else {
  48491. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48492. }
  48493. return this;
  48494. };
  48495. __decorate([
  48496. BABYLON.serializeAsVector3()
  48497. ], ShadowLight.prototype, "position", null);
  48498. __decorate([
  48499. BABYLON.serializeAsVector3()
  48500. ], ShadowLight.prototype, "direction", null);
  48501. __decorate([
  48502. BABYLON.serialize()
  48503. ], ShadowLight.prototype, "shadowMinZ", null);
  48504. __decorate([
  48505. BABYLON.serialize()
  48506. ], ShadowLight.prototype, "shadowMaxZ", null);
  48507. return ShadowLight;
  48508. }(BABYLON.Light));
  48509. BABYLON.ShadowLight = ShadowLight;
  48510. })(BABYLON || (BABYLON = {}));
  48511. //# sourceMappingURL=babylon.shadowLight.js.map
  48512. var BABYLON;
  48513. (function (BABYLON) {
  48514. /**
  48515. * A point light is a light defined by an unique point in world space.
  48516. * The light is emitted in every direction from this point.
  48517. * A good example of a point light is a standard light bulb.
  48518. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48519. */
  48520. var PointLight = /** @class */ (function (_super) {
  48521. __extends(PointLight, _super);
  48522. /**
  48523. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48524. * A PointLight emits the light in every direction.
  48525. * It can cast shadows.
  48526. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48527. * ```javascript
  48528. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48529. * ```
  48530. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48531. * @param name The light friendly name
  48532. * @param position The position of the point light in the scene
  48533. * @param scene The scene the lights belongs to
  48534. */
  48535. function PointLight(name, position, scene) {
  48536. var _this = _super.call(this, name, scene) || this;
  48537. _this._shadowAngle = Math.PI / 2;
  48538. _this.position = position;
  48539. return _this;
  48540. }
  48541. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48542. /**
  48543. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48544. * This specifies what angle the shadow will use to be created.
  48545. *
  48546. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48547. */
  48548. get: function () {
  48549. return this._shadowAngle;
  48550. },
  48551. /**
  48552. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48553. * This specifies what angle the shadow will use to be created.
  48554. *
  48555. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48556. */
  48557. set: function (value) {
  48558. this._shadowAngle = value;
  48559. this.forceProjectionMatrixCompute();
  48560. },
  48561. enumerable: true,
  48562. configurable: true
  48563. });
  48564. Object.defineProperty(PointLight.prototype, "direction", {
  48565. /**
  48566. * Gets the direction if it has been set.
  48567. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48568. */
  48569. get: function () {
  48570. return this._direction;
  48571. },
  48572. /**
  48573. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48574. */
  48575. set: function (value) {
  48576. var previousNeedCube = this.needCube();
  48577. this._direction = value;
  48578. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48579. this._shadowGenerator.recreateShadowMap();
  48580. }
  48581. },
  48582. enumerable: true,
  48583. configurable: true
  48584. });
  48585. /**
  48586. * Returns the string "PointLight"
  48587. * @returns the class name
  48588. */
  48589. PointLight.prototype.getClassName = function () {
  48590. return "PointLight";
  48591. };
  48592. /**
  48593. * Returns the integer 0.
  48594. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48595. */
  48596. PointLight.prototype.getTypeID = function () {
  48597. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48598. };
  48599. /**
  48600. * Specifies wether or not the shadowmap should be a cube texture.
  48601. * @returns true if the shadowmap needs to be a cube texture.
  48602. */
  48603. PointLight.prototype.needCube = function () {
  48604. return !this.direction;
  48605. };
  48606. /**
  48607. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48608. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48609. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48610. */
  48611. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48612. if (this.direction) {
  48613. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48614. }
  48615. else {
  48616. switch (faceIndex) {
  48617. case 0:
  48618. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48619. case 1:
  48620. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48621. case 2:
  48622. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48623. case 3:
  48624. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48625. case 4:
  48626. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48627. case 5:
  48628. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48629. }
  48630. }
  48631. return BABYLON.Vector3.Zero();
  48632. };
  48633. /**
  48634. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48635. * - fov = PI / 2
  48636. * - aspect ratio : 1.0
  48637. * - z-near and far equal to the active camera minZ and maxZ.
  48638. * Returns the PointLight.
  48639. */
  48640. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48641. var activeCamera = this.getScene().activeCamera;
  48642. if (!activeCamera) {
  48643. return;
  48644. }
  48645. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48646. };
  48647. PointLight.prototype._buildUniformLayout = function () {
  48648. this._uniformBuffer.addUniform("vLightData", 4);
  48649. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48650. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48651. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48652. this._uniformBuffer.addUniform("depthValues", 2);
  48653. this._uniformBuffer.create();
  48654. };
  48655. /**
  48656. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48657. * @param effect The effect to update
  48658. * @param lightIndex The index of the light in the effect to update
  48659. * @returns The point light
  48660. */
  48661. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48662. if (this.computeTransformedInformation()) {
  48663. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48664. return this;
  48665. }
  48666. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48667. return this;
  48668. };
  48669. __decorate([
  48670. BABYLON.serialize()
  48671. ], PointLight.prototype, "shadowAngle", null);
  48672. return PointLight;
  48673. }(BABYLON.ShadowLight));
  48674. BABYLON.PointLight = PointLight;
  48675. })(BABYLON || (BABYLON = {}));
  48676. //# sourceMappingURL=babylon.pointLight.js.map
  48677. var BABYLON;
  48678. (function (BABYLON) {
  48679. /**
  48680. * A directional light is defined by a direction (what a surprise!).
  48681. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48682. * 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.
  48683. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48684. */
  48685. var DirectionalLight = /** @class */ (function (_super) {
  48686. __extends(DirectionalLight, _super);
  48687. /**
  48688. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48689. * The directional light is emitted from everywhere in the given direction.
  48690. * It can cast shawdows.
  48691. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48692. * @param name The friendly name of the light
  48693. * @param direction The direction of the light
  48694. * @param scene The scene the light belongs to
  48695. */
  48696. function DirectionalLight(name, direction, scene) {
  48697. var _this = _super.call(this, name, scene) || this;
  48698. _this._shadowFrustumSize = 0;
  48699. _this._shadowOrthoScale = 0.1;
  48700. /**
  48701. * Automatically compute the projection matrix to best fit (including all the casters)
  48702. * on each frame.
  48703. */
  48704. _this.autoUpdateExtends = true;
  48705. // Cache
  48706. _this._orthoLeft = Number.MAX_VALUE;
  48707. _this._orthoRight = Number.MIN_VALUE;
  48708. _this._orthoTop = Number.MIN_VALUE;
  48709. _this._orthoBottom = Number.MAX_VALUE;
  48710. _this.position = direction.scale(-1.0);
  48711. _this.direction = direction;
  48712. return _this;
  48713. }
  48714. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48715. /**
  48716. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48717. */
  48718. get: function () {
  48719. return this._shadowFrustumSize;
  48720. },
  48721. /**
  48722. * Specifies a fix frustum size for the shadow generation.
  48723. */
  48724. set: function (value) {
  48725. this._shadowFrustumSize = value;
  48726. this.forceProjectionMatrixCompute();
  48727. },
  48728. enumerable: true,
  48729. configurable: true
  48730. });
  48731. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48732. /**
  48733. * Gets the shadow projection scale against the optimal computed one.
  48734. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48735. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48736. */
  48737. get: function () {
  48738. return this._shadowOrthoScale;
  48739. },
  48740. /**
  48741. * Sets the shadow projection scale against the optimal computed one.
  48742. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48743. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48744. */
  48745. set: function (value) {
  48746. this._shadowOrthoScale = value;
  48747. this.forceProjectionMatrixCompute();
  48748. },
  48749. enumerable: true,
  48750. configurable: true
  48751. });
  48752. /**
  48753. * Returns the string "DirectionalLight".
  48754. * @return The class name
  48755. */
  48756. DirectionalLight.prototype.getClassName = function () {
  48757. return "DirectionalLight";
  48758. };
  48759. /**
  48760. * Returns the integer 1.
  48761. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48762. */
  48763. DirectionalLight.prototype.getTypeID = function () {
  48764. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48765. };
  48766. /**
  48767. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48768. * Returns the DirectionalLight Shadow projection matrix.
  48769. */
  48770. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48771. if (this.shadowFrustumSize > 0) {
  48772. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48773. }
  48774. else {
  48775. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48776. }
  48777. };
  48778. /**
  48779. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48780. * Returns the DirectionalLight Shadow projection matrix.
  48781. */
  48782. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48783. var activeCamera = this.getScene().activeCamera;
  48784. if (!activeCamera) {
  48785. return;
  48786. }
  48787. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48788. };
  48789. /**
  48790. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48791. * Returns the DirectionalLight Shadow projection matrix.
  48792. */
  48793. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48794. var activeCamera = this.getScene().activeCamera;
  48795. if (!activeCamera) {
  48796. return;
  48797. }
  48798. // Check extends
  48799. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48800. var tempVector3 = BABYLON.Vector3.Zero();
  48801. this._orthoLeft = Number.MAX_VALUE;
  48802. this._orthoRight = Number.MIN_VALUE;
  48803. this._orthoTop = Number.MIN_VALUE;
  48804. this._orthoBottom = Number.MAX_VALUE;
  48805. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48806. var mesh = renderList[meshIndex];
  48807. if (!mesh) {
  48808. continue;
  48809. }
  48810. var boundingInfo = mesh.getBoundingInfo();
  48811. var boundingBox = boundingInfo.boundingBox;
  48812. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48813. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48814. if (tempVector3.x < this._orthoLeft)
  48815. this._orthoLeft = tempVector3.x;
  48816. if (tempVector3.y < this._orthoBottom)
  48817. this._orthoBottom = tempVector3.y;
  48818. if (tempVector3.x > this._orthoRight)
  48819. this._orthoRight = tempVector3.x;
  48820. if (tempVector3.y > this._orthoTop)
  48821. this._orthoTop = tempVector3.y;
  48822. }
  48823. }
  48824. }
  48825. var xOffset = this._orthoRight - this._orthoLeft;
  48826. var yOffset = this._orthoTop - this._orthoBottom;
  48827. 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);
  48828. };
  48829. DirectionalLight.prototype._buildUniformLayout = function () {
  48830. this._uniformBuffer.addUniform("vLightData", 4);
  48831. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48832. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48833. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48834. this._uniformBuffer.addUniform("depthValues", 2);
  48835. this._uniformBuffer.create();
  48836. };
  48837. /**
  48838. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48839. * @param effect The effect to update
  48840. * @param lightIndex The index of the light in the effect to update
  48841. * @returns The directional light
  48842. */
  48843. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48844. if (this.computeTransformedInformation()) {
  48845. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48846. return this;
  48847. }
  48848. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48849. return this;
  48850. };
  48851. /**
  48852. * Gets the minZ used for shadow according to both the scene and the light.
  48853. *
  48854. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48855. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48856. * @param activeCamera The camera we are returning the min for
  48857. * @returns the depth min z
  48858. */
  48859. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48860. return 1;
  48861. };
  48862. /**
  48863. * Gets the maxZ used for shadow according to both the scene and the light.
  48864. *
  48865. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48866. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48867. * @param activeCamera The camera we are returning the max for
  48868. * @returns the depth max z
  48869. */
  48870. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48871. return 1;
  48872. };
  48873. __decorate([
  48874. BABYLON.serialize()
  48875. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48876. __decorate([
  48877. BABYLON.serialize()
  48878. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48879. __decorate([
  48880. BABYLON.serialize()
  48881. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48882. return DirectionalLight;
  48883. }(BABYLON.ShadowLight));
  48884. BABYLON.DirectionalLight = DirectionalLight;
  48885. })(BABYLON || (BABYLON = {}));
  48886. //# sourceMappingURL=babylon.directionalLight.js.map
  48887. var BABYLON;
  48888. (function (BABYLON) {
  48889. /**
  48890. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48891. * These values define a cone of light starting from the position, emitting toward the direction.
  48892. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48893. * and the exponent defines the speed of the decay of the light with distance (reach).
  48894. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48895. */
  48896. var SpotLight = /** @class */ (function (_super) {
  48897. __extends(SpotLight, _super);
  48898. /**
  48899. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48900. * It can cast shadows.
  48901. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48902. * @param name The light friendly name
  48903. * @param position The position of the spot light in the scene
  48904. * @param direction The direction of the light in the scene
  48905. * @param angle The cone angle of the light in Radians
  48906. * @param exponent The light decay speed with the distance from the emission spot
  48907. * @param scene The scene the lights belongs to
  48908. */
  48909. function SpotLight(name, position, direction, angle, exponent, scene) {
  48910. var _this = _super.call(this, name, scene) || this;
  48911. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48912. _this._projectionTextureLightNear = 1e-6;
  48913. _this._projectionTextureLightFar = 1000.0;
  48914. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48915. _this._projectionTextureViewLightDirty = true;
  48916. _this._projectionTextureProjectionLightDirty = true;
  48917. _this._projectionTextureDirty = true;
  48918. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48919. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48920. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48921. _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);
  48922. _this.position = position;
  48923. _this.direction = direction;
  48924. _this.angle = angle;
  48925. _this.exponent = exponent;
  48926. return _this;
  48927. }
  48928. Object.defineProperty(SpotLight.prototype, "angle", {
  48929. /**
  48930. * Gets the cone angle of the spot light in Radians.
  48931. */
  48932. get: function () {
  48933. return this._angle;
  48934. },
  48935. /**
  48936. * Sets the cone angle of the spot light in Radians.
  48937. */
  48938. set: function (value) {
  48939. this._angle = value;
  48940. this._projectionTextureProjectionLightDirty = true;
  48941. this.forceProjectionMatrixCompute();
  48942. },
  48943. enumerable: true,
  48944. configurable: true
  48945. });
  48946. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48947. /**
  48948. * Allows scaling the angle of the light for shadow generation only.
  48949. */
  48950. get: function () {
  48951. return this._shadowAngleScale;
  48952. },
  48953. /**
  48954. * Allows scaling the angle of the light for shadow generation only.
  48955. */
  48956. set: function (value) {
  48957. this._shadowAngleScale = value;
  48958. this.forceProjectionMatrixCompute();
  48959. },
  48960. enumerable: true,
  48961. configurable: true
  48962. });
  48963. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48964. /**
  48965. * Allows reading the projecton texture
  48966. */
  48967. get: function () {
  48968. return this._projectionTextureMatrix;
  48969. },
  48970. enumerable: true,
  48971. configurable: true
  48972. });
  48973. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48974. /**
  48975. * Gets the near clip of the Spotlight for texture projection.
  48976. */
  48977. get: function () {
  48978. return this._projectionTextureLightNear;
  48979. },
  48980. /**
  48981. * Sets the near clip of the Spotlight for texture projection.
  48982. */
  48983. set: function (value) {
  48984. this._projectionTextureLightNear = value;
  48985. this._projectionTextureProjectionLightDirty = true;
  48986. },
  48987. enumerable: true,
  48988. configurable: true
  48989. });
  48990. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48991. /**
  48992. * Gets the far clip of the Spotlight for texture projection.
  48993. */
  48994. get: function () {
  48995. return this._projectionTextureLightFar;
  48996. },
  48997. /**
  48998. * Sets the far clip of the Spotlight for texture projection.
  48999. */
  49000. set: function (value) {
  49001. this._projectionTextureLightFar = value;
  49002. this._projectionTextureProjectionLightDirty = true;
  49003. },
  49004. enumerable: true,
  49005. configurable: true
  49006. });
  49007. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49008. /**
  49009. * Gets the Up vector of the Spotlight for texture projection.
  49010. */
  49011. get: function () {
  49012. return this._projectionTextureUpDirection;
  49013. },
  49014. /**
  49015. * Sets the Up vector of the Spotlight for texture projection.
  49016. */
  49017. set: function (value) {
  49018. this._projectionTextureUpDirection = value;
  49019. this._projectionTextureProjectionLightDirty = true;
  49020. },
  49021. enumerable: true,
  49022. configurable: true
  49023. });
  49024. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49025. /**
  49026. * Gets the projection texture of the light.
  49027. */
  49028. get: function () {
  49029. return this._projectionTexture;
  49030. },
  49031. /**
  49032. * Sets the projection texture of the light.
  49033. */
  49034. set: function (value) {
  49035. this._projectionTexture = value;
  49036. this._projectionTextureDirty = true;
  49037. },
  49038. enumerable: true,
  49039. configurable: true
  49040. });
  49041. /**
  49042. * Returns the string "SpotLight".
  49043. * @returns the class name
  49044. */
  49045. SpotLight.prototype.getClassName = function () {
  49046. return "SpotLight";
  49047. };
  49048. /**
  49049. * Returns the integer 2.
  49050. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49051. */
  49052. SpotLight.prototype.getTypeID = function () {
  49053. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49054. };
  49055. /**
  49056. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49057. */
  49058. SpotLight.prototype._setDirection = function (value) {
  49059. _super.prototype._setDirection.call(this, value);
  49060. this._projectionTextureViewLightDirty = true;
  49061. };
  49062. /**
  49063. * Overrides the position setter to recompute the projection texture view light Matrix.
  49064. */
  49065. SpotLight.prototype._setPosition = function (value) {
  49066. _super.prototype._setPosition.call(this, value);
  49067. this._projectionTextureViewLightDirty = true;
  49068. };
  49069. /**
  49070. * 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.
  49071. * Returns the SpotLight.
  49072. */
  49073. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49074. var activeCamera = this.getScene().activeCamera;
  49075. if (!activeCamera) {
  49076. return;
  49077. }
  49078. this._shadowAngleScale = this._shadowAngleScale || 1;
  49079. var angle = this._shadowAngleScale * this._angle;
  49080. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49081. };
  49082. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49083. this._projectionTextureViewLightDirty = false;
  49084. this._projectionTextureDirty = true;
  49085. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49086. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49087. };
  49088. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49089. this._projectionTextureProjectionLightDirty = false;
  49090. this._projectionTextureDirty = true;
  49091. var light_far = this.projectionTextureLightFar;
  49092. var light_near = this.projectionTextureLightNear;
  49093. var P = light_far / (light_far - light_near);
  49094. var Q = -P * light_near;
  49095. var S = 1.0 / Math.tan(this._angle / 2.0);
  49096. var A = 1.0;
  49097. 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);
  49098. };
  49099. /**
  49100. * Main function for light texture projection matrix computing.
  49101. */
  49102. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49103. this._projectionTextureDirty = false;
  49104. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49105. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49106. };
  49107. SpotLight.prototype._buildUniformLayout = function () {
  49108. this._uniformBuffer.addUniform("vLightData", 4);
  49109. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49110. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49111. this._uniformBuffer.addUniform("vLightDirection", 3);
  49112. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49113. this._uniformBuffer.addUniform("depthValues", 2);
  49114. this._uniformBuffer.create();
  49115. };
  49116. /**
  49117. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49118. * @param effect The effect to update
  49119. * @param lightIndex The index of the light in the effect to update
  49120. * @returns The spot light
  49121. */
  49122. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49123. var normalizeDirection;
  49124. if (this.computeTransformedInformation()) {
  49125. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49126. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49127. }
  49128. else {
  49129. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49130. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49131. }
  49132. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49133. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49134. if (this._projectionTextureViewLightDirty) {
  49135. this._computeProjectionTextureViewLightMatrix();
  49136. }
  49137. if (this._projectionTextureProjectionLightDirty) {
  49138. this._computeProjectionTextureProjectionLightMatrix();
  49139. }
  49140. if (this._projectionTextureDirty) {
  49141. this._computeProjectionTextureMatrix();
  49142. }
  49143. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49144. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49145. }
  49146. return this;
  49147. };
  49148. /**
  49149. * Disposes the light and the associated resources.
  49150. */
  49151. SpotLight.prototype.dispose = function () {
  49152. _super.prototype.dispose.call(this);
  49153. if (this._projectionTexture) {
  49154. this._projectionTexture.dispose();
  49155. }
  49156. };
  49157. __decorate([
  49158. BABYLON.serialize()
  49159. ], SpotLight.prototype, "angle", null);
  49160. __decorate([
  49161. BABYLON.serialize()
  49162. ], SpotLight.prototype, "shadowAngleScale", null);
  49163. __decorate([
  49164. BABYLON.serialize()
  49165. ], SpotLight.prototype, "exponent", void 0);
  49166. __decorate([
  49167. BABYLON.serialize()
  49168. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49169. __decorate([
  49170. BABYLON.serialize()
  49171. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49172. __decorate([
  49173. BABYLON.serialize()
  49174. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49175. __decorate([
  49176. BABYLON.serializeAsTexture("projectedLightTexture")
  49177. ], SpotLight.prototype, "_projectionTexture", void 0);
  49178. return SpotLight;
  49179. }(BABYLON.ShadowLight));
  49180. BABYLON.SpotLight = SpotLight;
  49181. })(BABYLON || (BABYLON = {}));
  49182. //# sourceMappingURL=babylon.spotLight.js.map
  49183. var BABYLON;
  49184. (function (BABYLON) {
  49185. /**
  49186. * Class used to override all child animations of a given target
  49187. */
  49188. var AnimationPropertiesOverride = /** @class */ (function () {
  49189. function AnimationPropertiesOverride() {
  49190. /**
  49191. * Gets or sets a value indicating if animation blending must be used
  49192. */
  49193. this.enableBlending = false;
  49194. /**
  49195. * Gets or sets the blending speed to use when enableBlending is true
  49196. */
  49197. this.blendingSpeed = 0.01;
  49198. /**
  49199. * Gets or sets the default loop mode to use
  49200. */
  49201. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49202. }
  49203. return AnimationPropertiesOverride;
  49204. }());
  49205. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49206. })(BABYLON || (BABYLON = {}));
  49207. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49208. var BABYLON;
  49209. (function (BABYLON) {
  49210. /**
  49211. * Represents the range of an animation
  49212. */
  49213. var AnimationRange = /** @class */ (function () {
  49214. /**
  49215. * Initializes the range of an animation
  49216. * @param name The name of the animation range
  49217. * @param from The starting frame of the animation
  49218. * @param to The ending frame of the animation
  49219. */
  49220. function AnimationRange(
  49221. /**The name of the animation range**/
  49222. name,
  49223. /**The starting frame of the animation */
  49224. from,
  49225. /**The ending frame of the animation*/
  49226. to) {
  49227. this.name = name;
  49228. this.from = from;
  49229. this.to = to;
  49230. }
  49231. /**
  49232. * Makes a copy of the animation range
  49233. * @returns A copy of the animation range
  49234. */
  49235. AnimationRange.prototype.clone = function () {
  49236. return new AnimationRange(this.name, this.from, this.to);
  49237. };
  49238. return AnimationRange;
  49239. }());
  49240. BABYLON.AnimationRange = AnimationRange;
  49241. /**
  49242. * Composed of a frame, and an action function
  49243. */
  49244. var AnimationEvent = /** @class */ (function () {
  49245. /**
  49246. * Initializes the animation event
  49247. * @param frame The frame for which the event is triggered
  49248. * @param action The event to perform when triggered
  49249. * @param onlyOnce Specifies if the event should be triggered only once
  49250. */
  49251. function AnimationEvent(
  49252. /** The frame for which the event is triggered **/
  49253. frame,
  49254. /** The event to perform when triggered **/
  49255. action,
  49256. /** Specifies if the event should be triggered only once**/
  49257. onlyOnce) {
  49258. this.frame = frame;
  49259. this.action = action;
  49260. this.onlyOnce = onlyOnce;
  49261. /**
  49262. * Specifies if the animation event is done
  49263. */
  49264. this.isDone = false;
  49265. }
  49266. /** @hidden */
  49267. AnimationEvent.prototype._clone = function () {
  49268. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49269. };
  49270. return AnimationEvent;
  49271. }());
  49272. BABYLON.AnimationEvent = AnimationEvent;
  49273. /**
  49274. * A cursor which tracks a point on a path
  49275. */
  49276. var PathCursor = /** @class */ (function () {
  49277. /**
  49278. * Initializes the path cursor
  49279. * @param path The path to track
  49280. */
  49281. function PathCursor(path) {
  49282. this.path = path;
  49283. /**
  49284. * Stores path cursor callbacks for when an onchange event is triggered
  49285. */
  49286. this._onchange = new Array();
  49287. /**
  49288. * The value of the path cursor
  49289. */
  49290. this.value = 0;
  49291. /**
  49292. * The animation array of the path cursor
  49293. */
  49294. this.animations = new Array();
  49295. }
  49296. /**
  49297. * Gets the cursor point on the path
  49298. * @returns A point on the path cursor at the cursor location
  49299. */
  49300. PathCursor.prototype.getPoint = function () {
  49301. var point = this.path.getPointAtLengthPosition(this.value);
  49302. return new BABYLON.Vector3(point.x, 0, point.y);
  49303. };
  49304. /**
  49305. * Moves the cursor ahead by the step amount
  49306. * @param step The amount to move the cursor forward
  49307. * @returns This path cursor
  49308. */
  49309. PathCursor.prototype.moveAhead = function (step) {
  49310. if (step === void 0) { step = 0.002; }
  49311. this.move(step);
  49312. return this;
  49313. };
  49314. /**
  49315. * Moves the cursor behind by the step amount
  49316. * @param step The amount to move the cursor back
  49317. * @returns This path cursor
  49318. */
  49319. PathCursor.prototype.moveBack = function (step) {
  49320. if (step === void 0) { step = 0.002; }
  49321. this.move(-step);
  49322. return this;
  49323. };
  49324. /**
  49325. * Moves the cursor by the step amount
  49326. * If the step amount is greater than one, an exception is thrown
  49327. * @param step The amount to move the cursor
  49328. * @returns This path cursor
  49329. */
  49330. PathCursor.prototype.move = function (step) {
  49331. if (Math.abs(step) > 1) {
  49332. throw "step size should be less than 1.";
  49333. }
  49334. this.value += step;
  49335. this.ensureLimits();
  49336. this.raiseOnChange();
  49337. return this;
  49338. };
  49339. /**
  49340. * Ensures that the value is limited between zero and one
  49341. * @returns This path cursor
  49342. */
  49343. PathCursor.prototype.ensureLimits = function () {
  49344. while (this.value > 1) {
  49345. this.value -= 1;
  49346. }
  49347. while (this.value < 0) {
  49348. this.value += 1;
  49349. }
  49350. return this;
  49351. };
  49352. /**
  49353. * Runs onchange callbacks on change (used by the animation engine)
  49354. * @returns This path cursor
  49355. */
  49356. PathCursor.prototype.raiseOnChange = function () {
  49357. var _this = this;
  49358. this._onchange.forEach(function (f) { return f(_this); });
  49359. return this;
  49360. };
  49361. /**
  49362. * Executes a function on change
  49363. * @param f A path cursor onchange callback
  49364. * @returns This path cursor
  49365. */
  49366. PathCursor.prototype.onchange = function (f) {
  49367. this._onchange.push(f);
  49368. return this;
  49369. };
  49370. return PathCursor;
  49371. }());
  49372. BABYLON.PathCursor = PathCursor;
  49373. /**
  49374. * Enum for the animation key frame interpolation type
  49375. */
  49376. var AnimationKeyInterpolation;
  49377. (function (AnimationKeyInterpolation) {
  49378. /**
  49379. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49380. */
  49381. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49382. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49383. /**
  49384. * Class used to store any kind of animation
  49385. */
  49386. var Animation = /** @class */ (function () {
  49387. /**
  49388. * Initializes the animation
  49389. * @param name Name of the animation
  49390. * @param targetProperty Property to animate
  49391. * @param framePerSecond The frames per second of the animation
  49392. * @param dataType The data type of the animation
  49393. * @param loopMode The loop mode of the animation
  49394. * @param enableBlendings Specifies if blending should be enabled
  49395. */
  49396. function Animation(
  49397. /**Name of the animation */
  49398. name,
  49399. /**Property to animate */
  49400. targetProperty,
  49401. /**The frames per second of the animation */
  49402. framePerSecond,
  49403. /**The data type of the animation */
  49404. dataType,
  49405. /**The loop mode of the animation */
  49406. loopMode,
  49407. /**Specifies if blending should be enabled */
  49408. enableBlending) {
  49409. this.name = name;
  49410. this.targetProperty = targetProperty;
  49411. this.framePerSecond = framePerSecond;
  49412. this.dataType = dataType;
  49413. this.loopMode = loopMode;
  49414. this.enableBlending = enableBlending;
  49415. /**
  49416. * @hidden Internal use only
  49417. */
  49418. this._runtimeAnimations = new Array();
  49419. /**
  49420. * The set of event that will be linked to this animation
  49421. */
  49422. this._events = new Array();
  49423. /**
  49424. * Stores the blending speed of the animation
  49425. */
  49426. this.blendingSpeed = 0.01;
  49427. /**
  49428. * Stores the animation ranges for the animation
  49429. */
  49430. this._ranges = {};
  49431. this.targetPropertyPath = targetProperty.split(".");
  49432. this.dataType = dataType;
  49433. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49434. }
  49435. /**
  49436. * @hidden Internal use
  49437. */
  49438. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49439. var dataType = undefined;
  49440. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49441. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49442. }
  49443. else if (from instanceof BABYLON.Quaternion) {
  49444. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49445. }
  49446. else if (from instanceof BABYLON.Vector3) {
  49447. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49448. }
  49449. else if (from instanceof BABYLON.Vector2) {
  49450. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49451. }
  49452. else if (from instanceof BABYLON.Color3) {
  49453. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49454. }
  49455. else if (from instanceof BABYLON.Size) {
  49456. dataType = Animation.ANIMATIONTYPE_SIZE;
  49457. }
  49458. if (dataType == undefined) {
  49459. return null;
  49460. }
  49461. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49462. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49463. animation.setKeys(keys);
  49464. if (easingFunction !== undefined) {
  49465. animation.setEasingFunction(easingFunction);
  49466. }
  49467. return animation;
  49468. };
  49469. /**
  49470. * Sets up an animation
  49471. * @param property The property to animate
  49472. * @param animationType The animation type to apply
  49473. * @param framePerSecond The frames per second of the animation
  49474. * @param easingFunction The easing function used in the animation
  49475. * @returns The created animation
  49476. */
  49477. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49478. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49479. animation.setEasingFunction(easingFunction);
  49480. return animation;
  49481. };
  49482. /**
  49483. * Create and start an animation on a node
  49484. * @param name defines the name of the global animation that will be run on all nodes
  49485. * @param node defines the root node where the animation will take place
  49486. * @param targetProperty defines property to animate
  49487. * @param framePerSecond defines the number of frame per second yo use
  49488. * @param totalFrame defines the number of frames in total
  49489. * @param from defines the initial value
  49490. * @param to defines the final value
  49491. * @param loopMode defines which loop mode you want to use (off by default)
  49492. * @param easingFunction defines the easing function to use (linear by default)
  49493. * @param onAnimationEnd defines the callback to call when animation end
  49494. * @returns the animatable created for this animation
  49495. */
  49496. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49497. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49498. if (!animation) {
  49499. return null;
  49500. }
  49501. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49502. };
  49503. /**
  49504. * Create and start an animation on a node and its descendants
  49505. * @param name defines the name of the global animation that will be run on all nodes
  49506. * @param node defines the root node where the animation will take place
  49507. * @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
  49508. * @param targetProperty defines property to animate
  49509. * @param framePerSecond defines the number of frame per second to use
  49510. * @param totalFrame defines the number of frames in total
  49511. * @param from defines the initial value
  49512. * @param to defines the final value
  49513. * @param loopMode defines which loop mode you want to use (off by default)
  49514. * @param easingFunction defines the easing function to use (linear by default)
  49515. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49516. * @returns the list of animatables created for all nodes
  49517. * @example https://www.babylonjs-playground.com/#MH0VLI
  49518. */
  49519. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49520. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49521. if (!animation) {
  49522. return null;
  49523. }
  49524. var scene = node.getScene();
  49525. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49526. };
  49527. /**
  49528. * Creates a new animation, merges it with the existing animations and starts it
  49529. * @param name Name of the animation
  49530. * @param node Node which contains the scene that begins the animations
  49531. * @param targetProperty Specifies which property to animate
  49532. * @param framePerSecond The frames per second of the animation
  49533. * @param totalFrame The total number of frames
  49534. * @param from The frame at the beginning of the animation
  49535. * @param to The frame at the end of the animation
  49536. * @param loopMode Specifies the loop mode of the animation
  49537. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49538. * @param onAnimationEnd Callback to run once the animation is complete
  49539. * @returns Nullable animation
  49540. */
  49541. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49542. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49543. if (!animation) {
  49544. return null;
  49545. }
  49546. node.animations.push(animation);
  49547. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49548. };
  49549. /**
  49550. * Transition property of an host to the target Value
  49551. * @param property The property to transition
  49552. * @param targetValue The target Value of the property
  49553. * @param host The object where the property to animate belongs
  49554. * @param scene Scene used to run the animation
  49555. * @param frameRate Framerate (in frame/s) to use
  49556. * @param transition The transition type we want to use
  49557. * @param duration The duration of the animation, in milliseconds
  49558. * @param onAnimationEnd Callback trigger at the end of the animation
  49559. * @returns Nullable animation
  49560. */
  49561. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49562. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49563. if (duration <= 0) {
  49564. host[property] = targetValue;
  49565. if (onAnimationEnd) {
  49566. onAnimationEnd();
  49567. }
  49568. return null;
  49569. }
  49570. var endFrame = frameRate * (duration / 1000);
  49571. transition.setKeys([{
  49572. frame: 0,
  49573. value: host[property].clone ? host[property].clone() : host[property]
  49574. },
  49575. {
  49576. frame: endFrame,
  49577. value: targetValue
  49578. }]);
  49579. if (!host.animations) {
  49580. host.animations = [];
  49581. }
  49582. host.animations.push(transition);
  49583. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49584. animation.onAnimationEnd = onAnimationEnd;
  49585. return animation;
  49586. };
  49587. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49588. /**
  49589. * Return the array of runtime animations currently using this animation
  49590. */
  49591. get: function () {
  49592. return this._runtimeAnimations;
  49593. },
  49594. enumerable: true,
  49595. configurable: true
  49596. });
  49597. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49598. /**
  49599. * Specifies if any of the runtime animations are currently running
  49600. */
  49601. get: function () {
  49602. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49603. var runtimeAnimation = _a[_i];
  49604. if (!runtimeAnimation.isStopped) {
  49605. return true;
  49606. }
  49607. }
  49608. return false;
  49609. },
  49610. enumerable: true,
  49611. configurable: true
  49612. });
  49613. // Methods
  49614. /**
  49615. * Converts the animation to a string
  49616. * @param fullDetails support for multiple levels of logging within scene loading
  49617. * @returns String form of the animation
  49618. */
  49619. Animation.prototype.toString = function (fullDetails) {
  49620. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49621. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49622. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49623. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49624. if (fullDetails) {
  49625. ret += ", Ranges: {";
  49626. var first = true;
  49627. for (var name in this._ranges) {
  49628. if (first) {
  49629. ret += ", ";
  49630. first = false;
  49631. }
  49632. ret += name;
  49633. }
  49634. ret += "}";
  49635. }
  49636. return ret;
  49637. };
  49638. /**
  49639. * Add an event to this animation
  49640. * @param event Event to add
  49641. */
  49642. Animation.prototype.addEvent = function (event) {
  49643. this._events.push(event);
  49644. };
  49645. /**
  49646. * Remove all events found at the given frame
  49647. * @param frame The frame to remove events from
  49648. */
  49649. Animation.prototype.removeEvents = function (frame) {
  49650. for (var index = 0; index < this._events.length; index++) {
  49651. if (this._events[index].frame === frame) {
  49652. this._events.splice(index, 1);
  49653. index--;
  49654. }
  49655. }
  49656. };
  49657. /**
  49658. * Retrieves all the events from the animation
  49659. * @returns Events from the animation
  49660. */
  49661. Animation.prototype.getEvents = function () {
  49662. return this._events;
  49663. };
  49664. /**
  49665. * Creates an animation range
  49666. * @param name Name of the animation range
  49667. * @param from Starting frame of the animation range
  49668. * @param to Ending frame of the animation
  49669. */
  49670. Animation.prototype.createRange = function (name, from, to) {
  49671. // check name not already in use; could happen for bones after serialized
  49672. if (!this._ranges[name]) {
  49673. this._ranges[name] = new AnimationRange(name, from, to);
  49674. }
  49675. };
  49676. /**
  49677. * Deletes an animation range by name
  49678. * @param name Name of the animation range to delete
  49679. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49680. */
  49681. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49682. if (deleteFrames === void 0) { deleteFrames = true; }
  49683. var range = this._ranges[name];
  49684. if (!range) {
  49685. return;
  49686. }
  49687. if (deleteFrames) {
  49688. var from = range.from;
  49689. var to = range.to;
  49690. // this loop MUST go high to low for multiple splices to work
  49691. for (var key = this._keys.length - 1; key >= 0; key--) {
  49692. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49693. this._keys.splice(key, 1);
  49694. }
  49695. }
  49696. }
  49697. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49698. };
  49699. /**
  49700. * Gets the animation range by name, or null if not defined
  49701. * @param name Name of the animation range
  49702. * @returns Nullable animation range
  49703. */
  49704. Animation.prototype.getRange = function (name) {
  49705. return this._ranges[name];
  49706. };
  49707. /**
  49708. * Gets the key frames from the animation
  49709. * @returns The key frames of the animation
  49710. */
  49711. Animation.prototype.getKeys = function () {
  49712. return this._keys;
  49713. };
  49714. /**
  49715. * Gets the highest frame rate of the animation
  49716. * @returns Highest frame rate of the animation
  49717. */
  49718. Animation.prototype.getHighestFrame = function () {
  49719. var ret = 0;
  49720. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49721. if (ret < this._keys[key].frame) {
  49722. ret = this._keys[key].frame;
  49723. }
  49724. }
  49725. return ret;
  49726. };
  49727. /**
  49728. * Gets the easing function of the animation
  49729. * @returns Easing function of the animation
  49730. */
  49731. Animation.prototype.getEasingFunction = function () {
  49732. return this._easingFunction;
  49733. };
  49734. /**
  49735. * Sets the easing function of the animation
  49736. * @param easingFunction A custom mathematical formula for animation
  49737. */
  49738. Animation.prototype.setEasingFunction = function (easingFunction) {
  49739. this._easingFunction = easingFunction;
  49740. };
  49741. /**
  49742. * Interpolates a scalar linearly
  49743. * @param startValue Start value of the animation curve
  49744. * @param endValue End value of the animation curve
  49745. * @param gradient Scalar amount to interpolate
  49746. * @returns Interpolated scalar value
  49747. */
  49748. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49749. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49750. };
  49751. /**
  49752. * Interpolates a scalar cubically
  49753. * @param startValue Start value of the animation curve
  49754. * @param outTangent End tangent of the animation
  49755. * @param endValue End value of the animation curve
  49756. * @param inTangent Start tangent of the animation curve
  49757. * @param gradient Scalar amount to interpolate
  49758. * @returns Interpolated scalar value
  49759. */
  49760. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49761. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49762. };
  49763. /**
  49764. * Interpolates a quaternion using a spherical linear interpolation
  49765. * @param startValue Start value of the animation curve
  49766. * @param endValue End value of the animation curve
  49767. * @param gradient Scalar amount to interpolate
  49768. * @returns Interpolated quaternion value
  49769. */
  49770. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49771. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49772. };
  49773. /**
  49774. * Interpolates a quaternion cubically
  49775. * @param startValue Start value of the animation curve
  49776. * @param outTangent End tangent of the animation curve
  49777. * @param endValue End value of the animation curve
  49778. * @param inTangent Start tangent of the animation curve
  49779. * @param gradient Scalar amount to interpolate
  49780. * @returns Interpolated quaternion value
  49781. */
  49782. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49783. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49784. };
  49785. /**
  49786. * Interpolates a Vector3 linearl
  49787. * @param startValue Start value of the animation curve
  49788. * @param endValue End value of the animation curve
  49789. * @param gradient Scalar amount to interpolate
  49790. * @returns Interpolated scalar value
  49791. */
  49792. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49793. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49794. };
  49795. /**
  49796. * Interpolates a Vector3 cubically
  49797. * @param startValue Start value of the animation curve
  49798. * @param outTangent End tangent of the animation
  49799. * @param endValue End value of the animation curve
  49800. * @param inTangent Start tangent of the animation curve
  49801. * @param gradient Scalar amount to interpolate
  49802. * @returns InterpolatedVector3 value
  49803. */
  49804. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49805. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49806. };
  49807. /**
  49808. * Interpolates a Vector2 linearly
  49809. * @param startValue Start value of the animation curve
  49810. * @param endValue End value of the animation curve
  49811. * @param gradient Scalar amount to interpolate
  49812. * @returns Interpolated Vector2 value
  49813. */
  49814. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49815. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49816. };
  49817. /**
  49818. * Interpolates a Vector2 cubically
  49819. * @param startValue Start value of the animation curve
  49820. * @param outTangent End tangent of the animation
  49821. * @param endValue End value of the animation curve
  49822. * @param inTangent Start tangent of the animation curve
  49823. * @param gradient Scalar amount to interpolate
  49824. * @returns Interpolated Vector2 value
  49825. */
  49826. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49827. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49828. };
  49829. /**
  49830. * Interpolates a size linearly
  49831. * @param startValue Start value of the animation curve
  49832. * @param endValue End value of the animation curve
  49833. * @param gradient Scalar amount to interpolate
  49834. * @returns Interpolated Size value
  49835. */
  49836. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49837. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49838. };
  49839. /**
  49840. * Interpolates a Color3 linearly
  49841. * @param startValue Start value of the animation curve
  49842. * @param endValue End value of the animation curve
  49843. * @param gradient Scalar amount to interpolate
  49844. * @returns Interpolated Color3 value
  49845. */
  49846. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49847. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49848. };
  49849. /**
  49850. * @hidden Internal use only
  49851. */
  49852. Animation.prototype._getKeyValue = function (value) {
  49853. if (typeof value === "function") {
  49854. return value();
  49855. }
  49856. return value;
  49857. };
  49858. /**
  49859. * @hidden Internal use only
  49860. */
  49861. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49862. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49863. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49864. }
  49865. var keys = this.getKeys();
  49866. // Try to get a hash to find the right key
  49867. 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));
  49868. if (keys[startKeyIndex].frame >= currentFrame) {
  49869. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49870. startKeyIndex--;
  49871. }
  49872. }
  49873. for (var key = startKeyIndex; key < keys.length; key++) {
  49874. var endKey = keys[key + 1];
  49875. if (endKey.frame >= currentFrame) {
  49876. var startKey = keys[key];
  49877. var startValue = this._getKeyValue(startKey.value);
  49878. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49879. return startValue;
  49880. }
  49881. var endValue = this._getKeyValue(endKey.value);
  49882. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49883. var frameDelta = endKey.frame - startKey.frame;
  49884. // gradient : percent of currentFrame between the frame inf and the frame sup
  49885. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49886. // check for easingFunction and correction of gradient
  49887. var easingFunction = this.getEasingFunction();
  49888. if (easingFunction != null) {
  49889. gradient = easingFunction.ease(gradient);
  49890. }
  49891. switch (this.dataType) {
  49892. // Float
  49893. case Animation.ANIMATIONTYPE_FLOAT:
  49894. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49895. switch (loopMode) {
  49896. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49897. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49898. return floatValue;
  49899. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49900. return offsetValue * repeatCount + floatValue;
  49901. }
  49902. break;
  49903. // Quaternion
  49904. case Animation.ANIMATIONTYPE_QUATERNION:
  49905. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49906. switch (loopMode) {
  49907. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49908. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49909. return quatValue;
  49910. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49911. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49912. }
  49913. return quatValue;
  49914. // Vector3
  49915. case Animation.ANIMATIONTYPE_VECTOR3:
  49916. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49917. switch (loopMode) {
  49918. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49919. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49920. return vec3Value;
  49921. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49922. return vec3Value.add(offsetValue.scale(repeatCount));
  49923. }
  49924. // Vector2
  49925. case Animation.ANIMATIONTYPE_VECTOR2:
  49926. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49927. switch (loopMode) {
  49928. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49929. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49930. return vec2Value;
  49931. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49932. return vec2Value.add(offsetValue.scale(repeatCount));
  49933. }
  49934. // Size
  49935. case Animation.ANIMATIONTYPE_SIZE:
  49936. switch (loopMode) {
  49937. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49938. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49939. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49940. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49941. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49942. }
  49943. // Color3
  49944. case Animation.ANIMATIONTYPE_COLOR3:
  49945. switch (loopMode) {
  49946. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49947. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49948. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49949. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49950. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49951. }
  49952. // Matrix
  49953. case Animation.ANIMATIONTYPE_MATRIX:
  49954. switch (loopMode) {
  49955. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49956. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49957. if (Animation.AllowMatricesInterpolation) {
  49958. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49959. }
  49960. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49961. return startValue;
  49962. }
  49963. default:
  49964. break;
  49965. }
  49966. break;
  49967. }
  49968. }
  49969. return this._getKeyValue(keys[keys.length - 1].value);
  49970. };
  49971. /**
  49972. * Defines the function to use to interpolate matrices
  49973. * @param startValue defines the start matrix
  49974. * @param endValue defines the end matrix
  49975. * @param gradient defines the gradient between both matrices
  49976. * @param result defines an optional target matrix where to store the interpolation
  49977. * @returns the interpolated matrix
  49978. */
  49979. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49980. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49981. if (result) {
  49982. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49983. return result;
  49984. }
  49985. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49986. }
  49987. if (result) {
  49988. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49989. return result;
  49990. }
  49991. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49992. };
  49993. /**
  49994. * Makes a copy of the animation
  49995. * @returns Cloned animation
  49996. */
  49997. Animation.prototype.clone = function () {
  49998. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49999. clone.enableBlending = this.enableBlending;
  50000. clone.blendingSpeed = this.blendingSpeed;
  50001. if (this._keys) {
  50002. clone.setKeys(this._keys);
  50003. }
  50004. if (this._ranges) {
  50005. clone._ranges = {};
  50006. for (var name in this._ranges) {
  50007. var range = this._ranges[name];
  50008. if (!range) {
  50009. continue;
  50010. }
  50011. clone._ranges[name] = range.clone();
  50012. }
  50013. }
  50014. return clone;
  50015. };
  50016. /**
  50017. * Sets the key frames of the animation
  50018. * @param values The animation key frames to set
  50019. */
  50020. Animation.prototype.setKeys = function (values) {
  50021. this._keys = values.slice(0);
  50022. };
  50023. /**
  50024. * Serializes the animation to an object
  50025. * @returns Serialized object
  50026. */
  50027. Animation.prototype.serialize = function () {
  50028. var serializationObject = {};
  50029. serializationObject.name = this.name;
  50030. serializationObject.property = this.targetProperty;
  50031. serializationObject.framePerSecond = this.framePerSecond;
  50032. serializationObject.dataType = this.dataType;
  50033. serializationObject.loopBehavior = this.loopMode;
  50034. serializationObject.enableBlending = this.enableBlending;
  50035. serializationObject.blendingSpeed = this.blendingSpeed;
  50036. var dataType = this.dataType;
  50037. serializationObject.keys = [];
  50038. var keys = this.getKeys();
  50039. for (var index = 0; index < keys.length; index++) {
  50040. var animationKey = keys[index];
  50041. var key = {};
  50042. key.frame = animationKey.frame;
  50043. switch (dataType) {
  50044. case Animation.ANIMATIONTYPE_FLOAT:
  50045. key.values = [animationKey.value];
  50046. break;
  50047. case Animation.ANIMATIONTYPE_QUATERNION:
  50048. case Animation.ANIMATIONTYPE_MATRIX:
  50049. case Animation.ANIMATIONTYPE_VECTOR3:
  50050. case Animation.ANIMATIONTYPE_COLOR3:
  50051. key.values = animationKey.value.asArray();
  50052. break;
  50053. }
  50054. serializationObject.keys.push(key);
  50055. }
  50056. serializationObject.ranges = [];
  50057. for (var name in this._ranges) {
  50058. var source = this._ranges[name];
  50059. if (!source) {
  50060. continue;
  50061. }
  50062. var range = {};
  50063. range.name = name;
  50064. range.from = source.from;
  50065. range.to = source.to;
  50066. serializationObject.ranges.push(range);
  50067. }
  50068. return serializationObject;
  50069. };
  50070. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50071. /**
  50072. * Get the float animation type
  50073. */
  50074. get: function () {
  50075. return Animation._ANIMATIONTYPE_FLOAT;
  50076. },
  50077. enumerable: true,
  50078. configurable: true
  50079. });
  50080. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50081. /**
  50082. * Get the Vector3 animation type
  50083. */
  50084. get: function () {
  50085. return Animation._ANIMATIONTYPE_VECTOR3;
  50086. },
  50087. enumerable: true,
  50088. configurable: true
  50089. });
  50090. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50091. /**
  50092. * Get the Vectpr2 animation type
  50093. */
  50094. get: function () {
  50095. return Animation._ANIMATIONTYPE_VECTOR2;
  50096. },
  50097. enumerable: true,
  50098. configurable: true
  50099. });
  50100. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50101. /**
  50102. * Get the Size animation type
  50103. */
  50104. get: function () {
  50105. return Animation._ANIMATIONTYPE_SIZE;
  50106. },
  50107. enumerable: true,
  50108. configurable: true
  50109. });
  50110. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50111. /**
  50112. * Get the Quaternion animation type
  50113. */
  50114. get: function () {
  50115. return Animation._ANIMATIONTYPE_QUATERNION;
  50116. },
  50117. enumerable: true,
  50118. configurable: true
  50119. });
  50120. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50121. /**
  50122. * Get the Matrix animation type
  50123. */
  50124. get: function () {
  50125. return Animation._ANIMATIONTYPE_MATRIX;
  50126. },
  50127. enumerable: true,
  50128. configurable: true
  50129. });
  50130. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50131. /**
  50132. * Get the Color3 animation type
  50133. */
  50134. get: function () {
  50135. return Animation._ANIMATIONTYPE_COLOR3;
  50136. },
  50137. enumerable: true,
  50138. configurable: true
  50139. });
  50140. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50141. /**
  50142. * Get the Relative Loop Mode
  50143. */
  50144. get: function () {
  50145. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50146. },
  50147. enumerable: true,
  50148. configurable: true
  50149. });
  50150. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50151. /**
  50152. * Get the Cycle Loop Mode
  50153. */
  50154. get: function () {
  50155. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50156. },
  50157. enumerable: true,
  50158. configurable: true
  50159. });
  50160. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50161. /**
  50162. * Get the Constant Loop Mode
  50163. */
  50164. get: function () {
  50165. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50166. },
  50167. enumerable: true,
  50168. configurable: true
  50169. });
  50170. /** @hidden */
  50171. Animation._UniversalLerp = function (left, right, amount) {
  50172. var constructor = left.constructor;
  50173. if (constructor.Lerp) { // Lerp supported
  50174. return constructor.Lerp(left, right, amount);
  50175. }
  50176. else if (constructor.Slerp) { // Slerp supported
  50177. return constructor.Slerp(left, right, amount);
  50178. }
  50179. else if (left.toFixed) { // Number
  50180. return left * (1.0 - amount) + amount * right;
  50181. }
  50182. else { // Blending not supported
  50183. return right;
  50184. }
  50185. };
  50186. /**
  50187. * Parses an animation object and creates an animation
  50188. * @param parsedAnimation Parsed animation object
  50189. * @returns Animation object
  50190. */
  50191. Animation.Parse = function (parsedAnimation) {
  50192. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50193. var dataType = parsedAnimation.dataType;
  50194. var keys = [];
  50195. var data;
  50196. var index;
  50197. if (parsedAnimation.enableBlending) {
  50198. animation.enableBlending = parsedAnimation.enableBlending;
  50199. }
  50200. if (parsedAnimation.blendingSpeed) {
  50201. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50202. }
  50203. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50204. var key = parsedAnimation.keys[index];
  50205. var inTangent;
  50206. var outTangent;
  50207. switch (dataType) {
  50208. case Animation.ANIMATIONTYPE_FLOAT:
  50209. data = key.values[0];
  50210. if (key.values.length >= 1) {
  50211. inTangent = key.values[1];
  50212. }
  50213. if (key.values.length >= 2) {
  50214. outTangent = key.values[2];
  50215. }
  50216. break;
  50217. case Animation.ANIMATIONTYPE_QUATERNION:
  50218. data = BABYLON.Quaternion.FromArray(key.values);
  50219. if (key.values.length >= 8) {
  50220. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50221. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50222. inTangent = _inTangent;
  50223. }
  50224. }
  50225. if (key.values.length >= 12) {
  50226. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50227. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50228. outTangent = _outTangent;
  50229. }
  50230. }
  50231. break;
  50232. case Animation.ANIMATIONTYPE_MATRIX:
  50233. data = BABYLON.Matrix.FromArray(key.values);
  50234. break;
  50235. case Animation.ANIMATIONTYPE_COLOR3:
  50236. data = BABYLON.Color3.FromArray(key.values);
  50237. break;
  50238. case Animation.ANIMATIONTYPE_VECTOR3:
  50239. default:
  50240. data = BABYLON.Vector3.FromArray(key.values);
  50241. break;
  50242. }
  50243. var keyData = {};
  50244. keyData.frame = key.frame;
  50245. keyData.value = data;
  50246. if (inTangent != undefined) {
  50247. keyData.inTangent = inTangent;
  50248. }
  50249. if (outTangent != undefined) {
  50250. keyData.outTangent = outTangent;
  50251. }
  50252. keys.push(keyData);
  50253. }
  50254. animation.setKeys(keys);
  50255. if (parsedAnimation.ranges) {
  50256. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50257. data = parsedAnimation.ranges[index];
  50258. animation.createRange(data.name, data.from, data.to);
  50259. }
  50260. }
  50261. return animation;
  50262. };
  50263. /**
  50264. * Appends the serialized animations from the source animations
  50265. * @param source Source containing the animations
  50266. * @param destination Target to store the animations
  50267. */
  50268. Animation.AppendSerializedAnimations = function (source, destination) {
  50269. if (source.animations) {
  50270. destination.animations = [];
  50271. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50272. var animation = source.animations[animationIndex];
  50273. destination.animations.push(animation.serialize());
  50274. }
  50275. }
  50276. };
  50277. /**
  50278. * Use matrix interpolation instead of using direct key value when animating matrices
  50279. */
  50280. Animation.AllowMatricesInterpolation = false;
  50281. /**
  50282. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50283. */
  50284. Animation.AllowMatrixDecomposeForInterpolation = true;
  50285. // Statics
  50286. /**
  50287. * Float animation type
  50288. */
  50289. Animation._ANIMATIONTYPE_FLOAT = 0;
  50290. /**
  50291. * Vector3 animation type
  50292. */
  50293. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50294. /**
  50295. * Quaternion animation type
  50296. */
  50297. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50298. /**
  50299. * Matrix animation type
  50300. */
  50301. Animation._ANIMATIONTYPE_MATRIX = 3;
  50302. /**
  50303. * Color3 animation type
  50304. */
  50305. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50306. /**
  50307. * Vector2 animation type
  50308. */
  50309. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50310. /**
  50311. * Size animation type
  50312. */
  50313. Animation._ANIMATIONTYPE_SIZE = 6;
  50314. /**
  50315. * Relative Loop Mode
  50316. */
  50317. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50318. /**
  50319. * Cycle Loop Mode
  50320. */
  50321. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50322. /**
  50323. * Constant Loop Mode
  50324. */
  50325. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50326. return Animation;
  50327. }());
  50328. BABYLON.Animation = Animation;
  50329. })(BABYLON || (BABYLON = {}));
  50330. //# sourceMappingURL=babylon.animation.js.map
  50331. var BABYLON;
  50332. (function (BABYLON) {
  50333. /**
  50334. * This class defines the direct association between an animation and a target
  50335. */
  50336. var TargetedAnimation = /** @class */ (function () {
  50337. function TargetedAnimation() {
  50338. }
  50339. return TargetedAnimation;
  50340. }());
  50341. BABYLON.TargetedAnimation = TargetedAnimation;
  50342. /**
  50343. * Use this class to create coordinated animations on multiple targets
  50344. */
  50345. var AnimationGroup = /** @class */ (function () {
  50346. function AnimationGroup(name, scene) {
  50347. if (scene === void 0) { scene = null; }
  50348. this.name = name;
  50349. this._targetedAnimations = new Array();
  50350. this._animatables = new Array();
  50351. this._from = Number.MAX_VALUE;
  50352. this._to = -Number.MAX_VALUE;
  50353. this._speedRatio = 1;
  50354. this.onAnimationEndObservable = new BABYLON.Observable();
  50355. /**
  50356. * This observable will notify when all animations have ended.
  50357. */
  50358. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50359. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50360. this._scene.animationGroups.push(this);
  50361. }
  50362. Object.defineProperty(AnimationGroup.prototype, "from", {
  50363. /**
  50364. * Gets the first frame
  50365. */
  50366. get: function () {
  50367. return this._from;
  50368. },
  50369. enumerable: true,
  50370. configurable: true
  50371. });
  50372. Object.defineProperty(AnimationGroup.prototype, "to", {
  50373. /**
  50374. * Gets the last frame
  50375. */
  50376. get: function () {
  50377. return this._to;
  50378. },
  50379. enumerable: true,
  50380. configurable: true
  50381. });
  50382. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50383. /**
  50384. * Define if the animations are started
  50385. */
  50386. get: function () {
  50387. return this._isStarted;
  50388. },
  50389. enumerable: true,
  50390. configurable: true
  50391. });
  50392. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50393. /**
  50394. * Gets or sets the speed ratio to use for all animations
  50395. */
  50396. get: function () {
  50397. return this._speedRatio;
  50398. },
  50399. /**
  50400. * Gets or sets the speed ratio to use for all animations
  50401. */
  50402. set: function (value) {
  50403. if (this._speedRatio === value) {
  50404. return;
  50405. }
  50406. this._speedRatio = value;
  50407. for (var index = 0; index < this._animatables.length; index++) {
  50408. var animatable = this._animatables[index];
  50409. animatable.speedRatio = this._speedRatio;
  50410. }
  50411. },
  50412. enumerable: true,
  50413. configurable: true
  50414. });
  50415. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50416. /**
  50417. * Gets the targeted animations for this animation group
  50418. */
  50419. get: function () {
  50420. return this._targetedAnimations;
  50421. },
  50422. enumerable: true,
  50423. configurable: true
  50424. });
  50425. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50426. /**
  50427. * returning the list of animatables controlled by this animation group.
  50428. */
  50429. get: function () {
  50430. return this._animatables;
  50431. },
  50432. enumerable: true,
  50433. configurable: true
  50434. });
  50435. /**
  50436. * Add an animation (with its target) in the group
  50437. * @param animation defines the animation we want to add
  50438. * @param target defines the target of the animation
  50439. * @returns the {BABYLON.TargetedAnimation} object
  50440. */
  50441. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50442. var targetedAnimation = {
  50443. animation: animation,
  50444. target: target
  50445. };
  50446. var keys = animation.getKeys();
  50447. if (this._from > keys[0].frame) {
  50448. this._from = keys[0].frame;
  50449. }
  50450. if (this._to < keys[keys.length - 1].frame) {
  50451. this._to = keys[keys.length - 1].frame;
  50452. }
  50453. this._targetedAnimations.push(targetedAnimation);
  50454. return targetedAnimation;
  50455. };
  50456. /**
  50457. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50458. * It can add constant keys at begin or end
  50459. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50460. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50461. */
  50462. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50463. if (beginFrame === void 0) { beginFrame = null; }
  50464. if (endFrame === void 0) { endFrame = null; }
  50465. if (beginFrame == null)
  50466. beginFrame = this._from;
  50467. if (endFrame == null)
  50468. endFrame = this._to;
  50469. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50470. var targetedAnimation = this._targetedAnimations[index];
  50471. var keys = targetedAnimation.animation.getKeys();
  50472. var startKey = keys[0];
  50473. var endKey = keys[keys.length - 1];
  50474. if (startKey.frame > beginFrame) {
  50475. var newKey = {
  50476. frame: beginFrame,
  50477. value: startKey.value,
  50478. inTangent: startKey.inTangent,
  50479. outTangent: startKey.outTangent,
  50480. interpolation: startKey.interpolation
  50481. };
  50482. keys.splice(0, 0, newKey);
  50483. }
  50484. if (endKey.frame < endFrame) {
  50485. var newKey = {
  50486. frame: endFrame,
  50487. value: endKey.value,
  50488. inTangent: endKey.outTangent,
  50489. outTangent: endKey.outTangent,
  50490. interpolation: endKey.interpolation
  50491. };
  50492. keys.push(newKey);
  50493. }
  50494. }
  50495. this._from = beginFrame;
  50496. this._to = endFrame;
  50497. return this;
  50498. };
  50499. /**
  50500. * Start all animations on given targets
  50501. * @param loop defines if animations must loop
  50502. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50503. * @param from defines the from key (optional)
  50504. * @param to defines the to key (optional)
  50505. * @returns the current animation group
  50506. */
  50507. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50508. var _this = this;
  50509. if (loop === void 0) { loop = false; }
  50510. if (speedRatio === void 0) { speedRatio = 1; }
  50511. if (this._isStarted || this._targetedAnimations.length === 0) {
  50512. return this;
  50513. }
  50514. var _loop_1 = function (targetedAnimation) {
  50515. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50516. animatable.onAnimationEnd = function () {
  50517. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50518. _this._checkAnimationGroupEnded(animatable);
  50519. };
  50520. this_1._animatables.push(animatable);
  50521. };
  50522. var this_1 = this;
  50523. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50524. var targetedAnimation = _a[_i];
  50525. _loop_1(targetedAnimation);
  50526. }
  50527. this._speedRatio = speedRatio;
  50528. this._isStarted = true;
  50529. return this;
  50530. };
  50531. /**
  50532. * Pause all animations
  50533. */
  50534. AnimationGroup.prototype.pause = function () {
  50535. if (!this._isStarted) {
  50536. return this;
  50537. }
  50538. for (var index = 0; index < this._animatables.length; index++) {
  50539. var animatable = this._animatables[index];
  50540. animatable.pause();
  50541. }
  50542. return this;
  50543. };
  50544. /**
  50545. * Play all animations to initial state
  50546. * This function will start() the animations if they were not started or will restart() them if they were paused
  50547. * @param loop defines if animations must loop
  50548. */
  50549. AnimationGroup.prototype.play = function (loop) {
  50550. // only if all animatables are ready and exist
  50551. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50552. if (loop !== undefined) {
  50553. for (var index = 0; index < this._animatables.length; index++) {
  50554. var animatable = this._animatables[index];
  50555. animatable.loopAnimation = loop;
  50556. }
  50557. }
  50558. this.restart();
  50559. }
  50560. else {
  50561. this.stop();
  50562. this.start(loop, this._speedRatio);
  50563. }
  50564. return this;
  50565. };
  50566. /**
  50567. * Reset all animations to initial state
  50568. */
  50569. AnimationGroup.prototype.reset = function () {
  50570. if (!this._isStarted) {
  50571. return this;
  50572. }
  50573. for (var index = 0; index < this._animatables.length; index++) {
  50574. var animatable = this._animatables[index];
  50575. animatable.reset();
  50576. }
  50577. return this;
  50578. };
  50579. /**
  50580. * Restart animations from key 0
  50581. */
  50582. AnimationGroup.prototype.restart = function () {
  50583. if (!this._isStarted) {
  50584. return this;
  50585. }
  50586. for (var index = 0; index < this._animatables.length; index++) {
  50587. var animatable = this._animatables[index];
  50588. animatable.restart();
  50589. }
  50590. return this;
  50591. };
  50592. /**
  50593. * Stop all animations
  50594. */
  50595. AnimationGroup.prototype.stop = function () {
  50596. if (!this._isStarted) {
  50597. return this;
  50598. }
  50599. var list = this._animatables.slice();
  50600. for (var index = 0; index < list.length; index++) {
  50601. list[index].stop();
  50602. }
  50603. this._isStarted = false;
  50604. return this;
  50605. };
  50606. /**
  50607. * Set animation weight for all animatables
  50608. * @param weight defines the weight to use
  50609. * @return the animationGroup
  50610. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50611. */
  50612. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50613. for (var index = 0; index < this._animatables.length; index++) {
  50614. var animatable = this._animatables[index];
  50615. animatable.weight = weight;
  50616. }
  50617. return this;
  50618. };
  50619. /**
  50620. * Synchronize and normalize all animatables with a source animatable
  50621. * @param root defines the root animatable to synchronize with
  50622. * @return the animationGroup
  50623. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50624. */
  50625. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50626. for (var index = 0; index < this._animatables.length; index++) {
  50627. var animatable = this._animatables[index];
  50628. animatable.syncWith(root);
  50629. }
  50630. return this;
  50631. };
  50632. /**
  50633. * Goes to a specific frame in this animation group
  50634. * @param frame the frame number to go to
  50635. * @return the animationGroup
  50636. */
  50637. AnimationGroup.prototype.goToFrame = function (frame) {
  50638. if (!this._isStarted) {
  50639. return this;
  50640. }
  50641. for (var index = 0; index < this._animatables.length; index++) {
  50642. var animatable = this._animatables[index];
  50643. animatable.goToFrame(frame);
  50644. }
  50645. return this;
  50646. };
  50647. /**
  50648. * Dispose all associated resources
  50649. */
  50650. AnimationGroup.prototype.dispose = function () {
  50651. this._targetedAnimations = [];
  50652. this._animatables = [];
  50653. var index = this._scene.animationGroups.indexOf(this);
  50654. if (index > -1) {
  50655. this._scene.animationGroups.splice(index, 1);
  50656. }
  50657. };
  50658. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50659. // animatable should be taken out of the array
  50660. var idx = this._animatables.indexOf(animatable);
  50661. if (idx > -1) {
  50662. this._animatables.splice(idx, 1);
  50663. }
  50664. // all animatables were removed? animation group ended!
  50665. if (this._animatables.length === 0) {
  50666. this._isStarted = false;
  50667. this.onAnimationGroupEndObservable.notifyObservers(this);
  50668. }
  50669. };
  50670. return AnimationGroup;
  50671. }());
  50672. BABYLON.AnimationGroup = AnimationGroup;
  50673. })(BABYLON || (BABYLON = {}));
  50674. //# sourceMappingURL=babylon.animationGroup.js.map
  50675. var BABYLON;
  50676. (function (BABYLON) {
  50677. /**
  50678. * Defines a runtime animation
  50679. */
  50680. var RuntimeAnimation = /** @class */ (function () {
  50681. /**
  50682. * Create a new RuntimeAnimation object
  50683. * @param target defines the target of the animation
  50684. * @param animation defines the source animation object
  50685. * @param scene defines the hosting scene
  50686. * @param host defines the initiating Animatable
  50687. */
  50688. function RuntimeAnimation(target, animation, scene, host) {
  50689. var _this = this;
  50690. this._events = new Array();
  50691. /**
  50692. * The current frame of the runtime animation
  50693. */
  50694. this._currentFrame = 0;
  50695. /**
  50696. * The original value of the runtime animation
  50697. */
  50698. this._originalValue = new Array();
  50699. /**
  50700. * The offsets cache of the runtime animation
  50701. */
  50702. this._offsetsCache = {};
  50703. /**
  50704. * The high limits cache of the runtime animation
  50705. */
  50706. this._highLimitsCache = {};
  50707. /**
  50708. * Specifies if the runtime animation has been stopped
  50709. */
  50710. this._stopped = false;
  50711. /**
  50712. * The blending factor of the runtime animation
  50713. */
  50714. this._blendingFactor = 0;
  50715. /**
  50716. * The target path of the runtime animation
  50717. */
  50718. this._targetPath = "";
  50719. /**
  50720. * The weight of the runtime animation
  50721. */
  50722. this._weight = 1.0;
  50723. /**
  50724. * The ratio offset of the runtime animation
  50725. */
  50726. this._ratioOffset = 0;
  50727. /**
  50728. * The previous delay of the runtime animation
  50729. */
  50730. this._previousDelay = 0;
  50731. /**
  50732. * The previous ratio of the runtime animation
  50733. */
  50734. this._previousRatio = 0;
  50735. this._animation = animation;
  50736. this._target = target;
  50737. this._scene = scene;
  50738. this._host = host;
  50739. animation._runtimeAnimations.push(this);
  50740. // Cloning events locally
  50741. var events = animation.getEvents();
  50742. if (events && events.length > 0) {
  50743. events.forEach(function (e) {
  50744. _this._events.push(e._clone());
  50745. });
  50746. }
  50747. }
  50748. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50749. /**
  50750. * Gets the current frame of the runtime animation
  50751. */
  50752. get: function () {
  50753. return this._currentFrame;
  50754. },
  50755. enumerable: true,
  50756. configurable: true
  50757. });
  50758. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50759. /**
  50760. * Gets the weight of the runtime animation
  50761. */
  50762. get: function () {
  50763. return this._weight;
  50764. },
  50765. enumerable: true,
  50766. configurable: true
  50767. });
  50768. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50769. /**
  50770. * Gets the current value of the runtime animation
  50771. */
  50772. get: function () {
  50773. return this._currentValue;
  50774. },
  50775. enumerable: true,
  50776. configurable: true
  50777. });
  50778. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50779. /**
  50780. * Gets the target path of the runtime animation
  50781. */
  50782. get: function () {
  50783. return this._targetPath;
  50784. },
  50785. enumerable: true,
  50786. configurable: true
  50787. });
  50788. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50789. /**
  50790. * Gets the actual target of the runtime animation
  50791. */
  50792. get: function () {
  50793. return this._activeTarget;
  50794. },
  50795. enumerable: true,
  50796. configurable: true
  50797. });
  50798. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50799. /**
  50800. * Gets the animation from the runtime animation
  50801. */
  50802. get: function () {
  50803. return this._animation;
  50804. },
  50805. enumerable: true,
  50806. configurable: true
  50807. });
  50808. /**
  50809. * Resets the runtime animation to the beginning
  50810. * @param restoreOriginal defines whether to restore the target property to the original value
  50811. */
  50812. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50813. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50814. if (restoreOriginal) {
  50815. if (this._target instanceof Array) {
  50816. var index = 0;
  50817. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50818. var target = _a[_i];
  50819. if (this._originalValue[index] !== undefined) {
  50820. this._setValue(target, this._originalValue[index], -1);
  50821. }
  50822. index++;
  50823. }
  50824. }
  50825. else {
  50826. if (this._originalValue[0] !== undefined) {
  50827. this._setValue(this._target, this._originalValue[0], -1);
  50828. }
  50829. }
  50830. }
  50831. this._offsetsCache = {};
  50832. this._highLimitsCache = {};
  50833. this._currentFrame = 0;
  50834. this._blendingFactor = 0;
  50835. this._originalValue = new Array();
  50836. // Events
  50837. for (var index = 0; index < this._events.length; index++) {
  50838. this._events[index].isDone = false;
  50839. }
  50840. };
  50841. /**
  50842. * Specifies if the runtime animation is stopped
  50843. * @returns Boolean specifying if the runtime animation is stopped
  50844. */
  50845. RuntimeAnimation.prototype.isStopped = function () {
  50846. return this._stopped;
  50847. };
  50848. /**
  50849. * Disposes of the runtime animation
  50850. */
  50851. RuntimeAnimation.prototype.dispose = function () {
  50852. var index = this._animation.runtimeAnimations.indexOf(this);
  50853. if (index > -1) {
  50854. this._animation.runtimeAnimations.splice(index, 1);
  50855. }
  50856. };
  50857. /**
  50858. * Interpolates the animation from the current frame
  50859. * @param currentFrame The frame to interpolate the animation to
  50860. * @param repeatCount The number of times that the animation should loop
  50861. * @param loopMode The type of looping mode to use
  50862. * @param offsetValue Animation offset value
  50863. * @param highLimitValue The high limit value
  50864. * @returns The interpolated value
  50865. */
  50866. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50867. this._currentFrame = currentFrame;
  50868. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50869. this._workValue = BABYLON.Matrix.Zero();
  50870. }
  50871. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50872. };
  50873. /**
  50874. * Apply the interpolated value to the target
  50875. * @param currentValue defines the value computed by the animation
  50876. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50877. */
  50878. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50879. if (weight === void 0) { weight = 1.0; }
  50880. if (this._target instanceof Array) {
  50881. var index = 0;
  50882. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50883. var target = _a[_i];
  50884. this._setValue(target, currentValue, weight, index);
  50885. index++;
  50886. }
  50887. }
  50888. else {
  50889. this._setValue(this._target, currentValue, weight);
  50890. }
  50891. };
  50892. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50893. if (targetIndex === void 0) { targetIndex = 0; }
  50894. // Set value
  50895. var path;
  50896. var destination;
  50897. var targetPropertyPath = this._animation.targetPropertyPath;
  50898. if (targetPropertyPath.length > 1) {
  50899. var property = target[targetPropertyPath[0]];
  50900. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50901. property = property[targetPropertyPath[index]];
  50902. }
  50903. path = targetPropertyPath[targetPropertyPath.length - 1];
  50904. destination = property;
  50905. }
  50906. else {
  50907. path = targetPropertyPath[0];
  50908. destination = target;
  50909. }
  50910. this._targetPath = path;
  50911. this._activeTarget = destination;
  50912. this._weight = weight;
  50913. if (this._originalValue[targetIndex] === undefined) {
  50914. var originalValue = void 0;
  50915. if (destination.getRestPose && path === "_matrix") { // For bones
  50916. originalValue = destination.getRestPose();
  50917. }
  50918. else {
  50919. originalValue = destination[path];
  50920. }
  50921. if (originalValue && originalValue.clone) {
  50922. this._originalValue[targetIndex] = originalValue.clone();
  50923. }
  50924. else {
  50925. this._originalValue[targetIndex] = originalValue;
  50926. }
  50927. }
  50928. // Blending
  50929. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50930. if (enableBlending && this._blendingFactor <= 1.0) {
  50931. if (!this._originalBlendValue) {
  50932. var originalValue = destination[path];
  50933. if (originalValue.clone) {
  50934. this._originalBlendValue = originalValue.clone();
  50935. }
  50936. else {
  50937. this._originalBlendValue = originalValue;
  50938. }
  50939. }
  50940. if (this._originalBlendValue.m) { // Matrix
  50941. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50942. if (this._currentValue) {
  50943. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50944. }
  50945. else {
  50946. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50947. }
  50948. }
  50949. else {
  50950. if (this._currentValue) {
  50951. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50952. }
  50953. else {
  50954. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50955. }
  50956. }
  50957. }
  50958. else {
  50959. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50960. }
  50961. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50962. this._blendingFactor += blendingSpeed;
  50963. }
  50964. else {
  50965. this._currentValue = currentValue;
  50966. }
  50967. if (weight !== -1.0) {
  50968. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50969. }
  50970. else {
  50971. destination[path] = this._currentValue;
  50972. }
  50973. if (target.markAsDirty) {
  50974. target.markAsDirty(this._animation.targetProperty);
  50975. }
  50976. };
  50977. /**
  50978. * Gets the loop pmode of the runtime animation
  50979. * @returns Loop Mode
  50980. */
  50981. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50982. if (this._target && this._target.animationPropertiesOverride) {
  50983. return this._target.animationPropertiesOverride.loopMode;
  50984. }
  50985. return this._animation.loopMode;
  50986. };
  50987. /**
  50988. * Move the current animation to a given frame
  50989. * @param frame defines the frame to move to
  50990. */
  50991. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50992. var keys = this._animation.getKeys();
  50993. if (frame < keys[0].frame) {
  50994. frame = keys[0].frame;
  50995. }
  50996. else if (frame > keys[keys.length - 1].frame) {
  50997. frame = keys[keys.length - 1].frame;
  50998. }
  50999. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51000. this.setValue(currentValue, -1);
  51001. };
  51002. /**
  51003. * @hidden Internal use only
  51004. */
  51005. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51006. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51007. this._ratioOffset = this._previousRatio - newRatio;
  51008. };
  51009. /**
  51010. * Execute the current animation
  51011. * @param delay defines the delay to add to the current frame
  51012. * @param from defines the lower bound of the animation range
  51013. * @param to defines the upper bound of the animation range
  51014. * @param loop defines if the current animation must loop
  51015. * @param speedRatio defines the current speed ratio
  51016. * @param weight defines the weight of the animation (default is -1 so no weight)
  51017. * @returns a boolean indicating if the animation has ended
  51018. */
  51019. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51020. if (weight === void 0) { weight = -1.0; }
  51021. var targetPropertyPath = this._animation.targetPropertyPath;
  51022. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51023. this._stopped = true;
  51024. return false;
  51025. }
  51026. var keys = this._animation.getKeys();
  51027. // Return immediately if there is only one key frame.
  51028. if (keys.length === 1) {
  51029. this.setValue(keys[0].value, weight);
  51030. return !loop;
  51031. }
  51032. var returnValue = true;
  51033. // Adding a start key at frame 0 if missing
  51034. if (keys[0].frame !== 0) {
  51035. var newKey = { frame: 0, value: keys[0].value };
  51036. keys.splice(0, 0, newKey);
  51037. }
  51038. // Check limits
  51039. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51040. from = keys[0].frame;
  51041. }
  51042. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51043. to = keys[keys.length - 1].frame;
  51044. }
  51045. //to and from cannot be the same key
  51046. if (from === to) {
  51047. if (from > keys[0].frame) {
  51048. from--;
  51049. }
  51050. else if (to < keys[keys.length - 1].frame) {
  51051. to++;
  51052. }
  51053. }
  51054. // Compute ratio
  51055. var range = to - from;
  51056. var offsetValue;
  51057. // ratio represents the frame delta between from and to
  51058. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51059. var highLimitValue = 0;
  51060. this._previousDelay = delay;
  51061. this._previousRatio = ratio;
  51062. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51063. returnValue = false;
  51064. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51065. }
  51066. else {
  51067. // Get max value if required
  51068. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51069. var keyOffset = to.toString() + from.toString();
  51070. if (!this._offsetsCache[keyOffset]) {
  51071. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51072. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51073. switch (this._animation.dataType) {
  51074. // Float
  51075. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51076. this._offsetsCache[keyOffset] = toValue - fromValue;
  51077. break;
  51078. // Quaternion
  51079. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51080. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51081. break;
  51082. // Vector3
  51083. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51084. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51085. // Vector2
  51086. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51087. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51088. // Size
  51089. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51090. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51091. // Color3
  51092. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51093. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51094. default:
  51095. break;
  51096. }
  51097. this._highLimitsCache[keyOffset] = toValue;
  51098. }
  51099. highLimitValue = this._highLimitsCache[keyOffset];
  51100. offsetValue = this._offsetsCache[keyOffset];
  51101. }
  51102. }
  51103. if (offsetValue === undefined) {
  51104. switch (this._animation.dataType) {
  51105. // Float
  51106. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51107. offsetValue = 0;
  51108. break;
  51109. // Quaternion
  51110. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51111. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51112. break;
  51113. // Vector3
  51114. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51115. offsetValue = BABYLON.Vector3.Zero();
  51116. break;
  51117. // Vector2
  51118. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51119. offsetValue = BABYLON.Vector2.Zero();
  51120. break;
  51121. // Size
  51122. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51123. offsetValue = BABYLON.Size.Zero();
  51124. break;
  51125. // Color3
  51126. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51127. offsetValue = BABYLON.Color3.Black();
  51128. }
  51129. }
  51130. // Compute value
  51131. var repeatCount = (ratio / range) >> 0;
  51132. var currentFrame = returnValue ? from + ratio % range : to;
  51133. // Need to normalize?
  51134. if (this._host && this._host.syncRoot) {
  51135. var syncRoot = this._host.syncRoot;
  51136. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51137. currentFrame = from + (to - from) * hostNormalizedFrame;
  51138. }
  51139. // Reset events if looping
  51140. var events = this._events;
  51141. if (range > 0 && this.currentFrame > currentFrame ||
  51142. range < 0 && this.currentFrame < currentFrame) {
  51143. // Need to reset animation events
  51144. for (var index = 0; index < events.length; index++) {
  51145. if (!events[index].onlyOnce) {
  51146. // reset event, the animation is looping
  51147. events[index].isDone = false;
  51148. }
  51149. }
  51150. }
  51151. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51152. // Set value
  51153. this.setValue(currentValue, weight);
  51154. // Check events
  51155. for (var index = 0; index < events.length; index++) {
  51156. // Make sure current frame has passed event frame and that event frame is within the current range
  51157. // Also, handle both forward and reverse animations
  51158. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51159. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51160. var event = events[index];
  51161. if (!event.isDone) {
  51162. // If event should be done only once, remove it.
  51163. if (event.onlyOnce) {
  51164. events.splice(index, 1);
  51165. index--;
  51166. }
  51167. event.isDone = true;
  51168. event.action();
  51169. } // Don't do anything if the event has already be done.
  51170. }
  51171. }
  51172. if (!returnValue) {
  51173. this._stopped = true;
  51174. }
  51175. return returnValue;
  51176. };
  51177. return RuntimeAnimation;
  51178. }());
  51179. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51180. })(BABYLON || (BABYLON = {}));
  51181. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51182. var BABYLON;
  51183. (function (BABYLON) {
  51184. /**
  51185. * Class used to store an actual running animation
  51186. */
  51187. var Animatable = /** @class */ (function () {
  51188. /**
  51189. * Creates a new Animatable
  51190. * @param scene defines the hosting scene
  51191. * @param target defines the target object
  51192. * @param fromFrame defines the starting frame number (default is 0)
  51193. * @param toFrame defines the ending frame number (default is 100)
  51194. * @param loopAnimation defines if the animation must loop (default is false)
  51195. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51196. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51197. * @param animations defines a group of animation to add to the new Animatable
  51198. */
  51199. function Animatable(scene,
  51200. /** defines the target object */
  51201. target,
  51202. /** defines the starting frame number (default is 0) */
  51203. fromFrame,
  51204. /** defines the ending frame number (default is 100) */
  51205. toFrame,
  51206. /** defines if the animation must loop (default is false) */
  51207. loopAnimation, speedRatio,
  51208. /** defines a callback to call when animation ends if it is not looping */
  51209. onAnimationEnd, animations) {
  51210. if (fromFrame === void 0) { fromFrame = 0; }
  51211. if (toFrame === void 0) { toFrame = 100; }
  51212. if (loopAnimation === void 0) { loopAnimation = false; }
  51213. if (speedRatio === void 0) { speedRatio = 1.0; }
  51214. this.target = target;
  51215. this.fromFrame = fromFrame;
  51216. this.toFrame = toFrame;
  51217. this.loopAnimation = loopAnimation;
  51218. this.onAnimationEnd = onAnimationEnd;
  51219. this._localDelayOffset = null;
  51220. this._pausedDelay = null;
  51221. this._runtimeAnimations = new Array();
  51222. this._paused = false;
  51223. this._speedRatio = 1;
  51224. this._weight = -1.0;
  51225. /**
  51226. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51227. * This will only apply for non looping animation (default is true)
  51228. */
  51229. this.disposeOnEnd = true;
  51230. /**
  51231. * Gets a boolean indicating if the animation has started
  51232. */
  51233. this.animationStarted = false;
  51234. /**
  51235. * Observer raised when the animation ends
  51236. */
  51237. this.onAnimationEndObservable = new BABYLON.Observable();
  51238. this._scene = scene;
  51239. if (animations) {
  51240. this.appendAnimations(target, animations);
  51241. }
  51242. this._speedRatio = speedRatio;
  51243. scene._activeAnimatables.push(this);
  51244. }
  51245. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51246. /**
  51247. * Gets the root Animatable used to synchronize and normalize animations
  51248. */
  51249. get: function () {
  51250. return this._syncRoot;
  51251. },
  51252. enumerable: true,
  51253. configurable: true
  51254. });
  51255. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51256. /**
  51257. * Gets the current frame of the first RuntimeAnimation
  51258. * Used to synchronize Animatables
  51259. */
  51260. get: function () {
  51261. if (this._runtimeAnimations.length === 0) {
  51262. return 0;
  51263. }
  51264. return this._runtimeAnimations[0].currentFrame;
  51265. },
  51266. enumerable: true,
  51267. configurable: true
  51268. });
  51269. Object.defineProperty(Animatable.prototype, "weight", {
  51270. /**
  51271. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51272. */
  51273. get: function () {
  51274. return this._weight;
  51275. },
  51276. set: function (value) {
  51277. if (value === -1) { // -1 is ok and means no weight
  51278. this._weight = -1;
  51279. return;
  51280. }
  51281. // Else weight must be in [0, 1] range
  51282. this._weight = Math.min(Math.max(value, 0), 1.0);
  51283. },
  51284. enumerable: true,
  51285. configurable: true
  51286. });
  51287. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51288. /**
  51289. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51290. */
  51291. get: function () {
  51292. return this._speedRatio;
  51293. },
  51294. set: function (value) {
  51295. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51296. var animation = this._runtimeAnimations[index];
  51297. animation._prepareForSpeedRatioChange(value);
  51298. }
  51299. this._speedRatio = value;
  51300. },
  51301. enumerable: true,
  51302. configurable: true
  51303. });
  51304. // Methods
  51305. /**
  51306. * Synchronize and normalize current Animatable with a source Animatable
  51307. * This is useful when using animation weights and when animations are not of the same length
  51308. * @param root defines the root Animatable to synchronize with
  51309. * @returns the current Animatable
  51310. */
  51311. Animatable.prototype.syncWith = function (root) {
  51312. this._syncRoot = root;
  51313. if (root) {
  51314. // Make sure this animatable will animate after the root
  51315. var index = this._scene._activeAnimatables.indexOf(this);
  51316. if (index > -1) {
  51317. this._scene._activeAnimatables.splice(index, 1);
  51318. this._scene._activeAnimatables.push(this);
  51319. }
  51320. }
  51321. return this;
  51322. };
  51323. /**
  51324. * Gets the list of runtime animations
  51325. * @returns an array of RuntimeAnimation
  51326. */
  51327. Animatable.prototype.getAnimations = function () {
  51328. return this._runtimeAnimations;
  51329. };
  51330. /**
  51331. * Adds more animations to the current animatable
  51332. * @param target defines the target of the animations
  51333. * @param animations defines the new animations to add
  51334. */
  51335. Animatable.prototype.appendAnimations = function (target, animations) {
  51336. for (var index = 0; index < animations.length; index++) {
  51337. var animation = animations[index];
  51338. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51339. }
  51340. };
  51341. /**
  51342. * Gets the source animation for a specific property
  51343. * @param property defines the propertyu to look for
  51344. * @returns null or the source animation for the given property
  51345. */
  51346. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51347. var runtimeAnimations = this._runtimeAnimations;
  51348. for (var index = 0; index < runtimeAnimations.length; index++) {
  51349. if (runtimeAnimations[index].animation.targetProperty === property) {
  51350. return runtimeAnimations[index].animation;
  51351. }
  51352. }
  51353. return null;
  51354. };
  51355. /**
  51356. * Gets the runtime animation for a specific property
  51357. * @param property defines the propertyu to look for
  51358. * @returns null or the runtime animation for the given property
  51359. */
  51360. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51361. var runtimeAnimations = this._runtimeAnimations;
  51362. for (var index = 0; index < runtimeAnimations.length; index++) {
  51363. if (runtimeAnimations[index].animation.targetProperty === property) {
  51364. return runtimeAnimations[index];
  51365. }
  51366. }
  51367. return null;
  51368. };
  51369. /**
  51370. * Resets the animatable to its original state
  51371. */
  51372. Animatable.prototype.reset = function () {
  51373. var runtimeAnimations = this._runtimeAnimations;
  51374. for (var index = 0; index < runtimeAnimations.length; index++) {
  51375. runtimeAnimations[index].reset(true);
  51376. }
  51377. this._localDelayOffset = null;
  51378. this._pausedDelay = null;
  51379. };
  51380. /**
  51381. * Allows the animatable to blend with current running animations
  51382. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51383. * @param blendingSpeed defines the blending speed to use
  51384. */
  51385. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51386. var runtimeAnimations = this._runtimeAnimations;
  51387. for (var index = 0; index < runtimeAnimations.length; index++) {
  51388. runtimeAnimations[index].animation.enableBlending = true;
  51389. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51390. }
  51391. };
  51392. /**
  51393. * Disable animation blending
  51394. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51395. */
  51396. Animatable.prototype.disableBlending = function () {
  51397. var runtimeAnimations = this._runtimeAnimations;
  51398. for (var index = 0; index < runtimeAnimations.length; index++) {
  51399. runtimeAnimations[index].animation.enableBlending = false;
  51400. }
  51401. };
  51402. /**
  51403. * Jump directly to a given frame
  51404. * @param frame defines the frame to jump to
  51405. */
  51406. Animatable.prototype.goToFrame = function (frame) {
  51407. var runtimeAnimations = this._runtimeAnimations;
  51408. if (runtimeAnimations[0]) {
  51409. var fps = runtimeAnimations[0].animation.framePerSecond;
  51410. var currentFrame = runtimeAnimations[0].currentFrame;
  51411. var adjustTime = frame - currentFrame;
  51412. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51413. if (this._localDelayOffset === null) {
  51414. this._localDelayOffset = 0;
  51415. }
  51416. this._localDelayOffset -= delay;
  51417. }
  51418. for (var index = 0; index < runtimeAnimations.length; index++) {
  51419. runtimeAnimations[index].goToFrame(frame);
  51420. }
  51421. };
  51422. /**
  51423. * Pause the animation
  51424. */
  51425. Animatable.prototype.pause = function () {
  51426. if (this._paused) {
  51427. return;
  51428. }
  51429. this._paused = true;
  51430. };
  51431. /**
  51432. * Restart the animation
  51433. */
  51434. Animatable.prototype.restart = function () {
  51435. this._paused = false;
  51436. };
  51437. Animatable.prototype._raiseOnAnimationEnd = function () {
  51438. if (this.onAnimationEnd) {
  51439. this.onAnimationEnd();
  51440. }
  51441. this.onAnimationEndObservable.notifyObservers(this);
  51442. };
  51443. /**
  51444. * Stop and delete the current animation
  51445. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51446. */
  51447. Animatable.prototype.stop = function (animationName) {
  51448. if (animationName) {
  51449. var idx = this._scene._activeAnimatables.indexOf(this);
  51450. if (idx > -1) {
  51451. var runtimeAnimations = this._runtimeAnimations;
  51452. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51453. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51454. continue;
  51455. }
  51456. runtimeAnimations[index].dispose();
  51457. runtimeAnimations.splice(index, 1);
  51458. }
  51459. if (runtimeAnimations.length == 0) {
  51460. this._scene._activeAnimatables.splice(idx, 1);
  51461. this._raiseOnAnimationEnd();
  51462. }
  51463. }
  51464. }
  51465. else {
  51466. var index = this._scene._activeAnimatables.indexOf(this);
  51467. if (index > -1) {
  51468. this._scene._activeAnimatables.splice(index, 1);
  51469. var runtimeAnimations = this._runtimeAnimations;
  51470. for (var index = 0; index < runtimeAnimations.length; index++) {
  51471. runtimeAnimations[index].dispose();
  51472. }
  51473. this._raiseOnAnimationEnd();
  51474. }
  51475. }
  51476. };
  51477. /**
  51478. * Wait asynchronously for the animation to end
  51479. * @returns a promise which will be fullfilled when the animation ends
  51480. */
  51481. Animatable.prototype.waitAsync = function () {
  51482. var _this = this;
  51483. return new Promise(function (resolve, reject) {
  51484. _this.onAnimationEndObservable.add(function () {
  51485. resolve(_this);
  51486. }, undefined, undefined, _this, true);
  51487. });
  51488. };
  51489. /** @hidden */
  51490. Animatable.prototype._animate = function (delay) {
  51491. if (this._paused) {
  51492. this.animationStarted = false;
  51493. if (this._pausedDelay === null) {
  51494. this._pausedDelay = delay;
  51495. }
  51496. return true;
  51497. }
  51498. if (this._localDelayOffset === null) {
  51499. this._localDelayOffset = delay;
  51500. this._pausedDelay = null;
  51501. }
  51502. else if (this._pausedDelay !== null) {
  51503. this._localDelayOffset += delay - this._pausedDelay;
  51504. this._pausedDelay = null;
  51505. }
  51506. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51507. return true;
  51508. }
  51509. // Animating
  51510. var running = false;
  51511. var runtimeAnimations = this._runtimeAnimations;
  51512. var index;
  51513. for (index = 0; index < runtimeAnimations.length; index++) {
  51514. var animation = runtimeAnimations[index];
  51515. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51516. running = running || isRunning;
  51517. }
  51518. this.animationStarted = running;
  51519. if (!running) {
  51520. if (this.disposeOnEnd) {
  51521. // Remove from active animatables
  51522. index = this._scene._activeAnimatables.indexOf(this);
  51523. this._scene._activeAnimatables.splice(index, 1);
  51524. // Dispose all runtime animations
  51525. for (index = 0; index < runtimeAnimations.length; index++) {
  51526. runtimeAnimations[index].dispose();
  51527. }
  51528. }
  51529. this._raiseOnAnimationEnd();
  51530. if (this.disposeOnEnd) {
  51531. this.onAnimationEnd = null;
  51532. this.onAnimationEndObservable.clear();
  51533. }
  51534. }
  51535. return running;
  51536. };
  51537. return Animatable;
  51538. }());
  51539. BABYLON.Animatable = Animatable;
  51540. })(BABYLON || (BABYLON = {}));
  51541. //# sourceMappingURL=babylon.animatable.js.map
  51542. var BABYLON;
  51543. (function (BABYLON) {
  51544. var EasingFunction = /** @class */ (function () {
  51545. function EasingFunction() {
  51546. // Properties
  51547. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51548. }
  51549. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51550. get: function () {
  51551. return EasingFunction._EASINGMODE_EASEIN;
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51557. get: function () {
  51558. return EasingFunction._EASINGMODE_EASEOUT;
  51559. },
  51560. enumerable: true,
  51561. configurable: true
  51562. });
  51563. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51564. get: function () {
  51565. return EasingFunction._EASINGMODE_EASEINOUT;
  51566. },
  51567. enumerable: true,
  51568. configurable: true
  51569. });
  51570. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51571. var n = Math.min(Math.max(easingMode, 0), 2);
  51572. this._easingMode = n;
  51573. };
  51574. EasingFunction.prototype.getEasingMode = function () {
  51575. return this._easingMode;
  51576. };
  51577. EasingFunction.prototype.easeInCore = function (gradient) {
  51578. throw new Error('You must implement this method');
  51579. };
  51580. EasingFunction.prototype.ease = function (gradient) {
  51581. switch (this._easingMode) {
  51582. case EasingFunction.EASINGMODE_EASEIN:
  51583. return this.easeInCore(gradient);
  51584. case EasingFunction.EASINGMODE_EASEOUT:
  51585. return (1 - this.easeInCore(1 - gradient));
  51586. }
  51587. if (gradient >= 0.5) {
  51588. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51589. }
  51590. return (this.easeInCore(gradient * 2) * 0.5);
  51591. };
  51592. //Statics
  51593. EasingFunction._EASINGMODE_EASEIN = 0;
  51594. EasingFunction._EASINGMODE_EASEOUT = 1;
  51595. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51596. return EasingFunction;
  51597. }());
  51598. BABYLON.EasingFunction = EasingFunction;
  51599. var CircleEase = /** @class */ (function (_super) {
  51600. __extends(CircleEase, _super);
  51601. function CircleEase() {
  51602. return _super !== null && _super.apply(this, arguments) || this;
  51603. }
  51604. CircleEase.prototype.easeInCore = function (gradient) {
  51605. gradient = Math.max(0, Math.min(1, gradient));
  51606. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51607. };
  51608. return CircleEase;
  51609. }(EasingFunction));
  51610. BABYLON.CircleEase = CircleEase;
  51611. var BackEase = /** @class */ (function (_super) {
  51612. __extends(BackEase, _super);
  51613. function BackEase(amplitude) {
  51614. if (amplitude === void 0) { amplitude = 1; }
  51615. var _this = _super.call(this) || this;
  51616. _this.amplitude = amplitude;
  51617. return _this;
  51618. }
  51619. BackEase.prototype.easeInCore = function (gradient) {
  51620. var num = Math.max(0, this.amplitude);
  51621. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51622. };
  51623. return BackEase;
  51624. }(EasingFunction));
  51625. BABYLON.BackEase = BackEase;
  51626. var BounceEase = /** @class */ (function (_super) {
  51627. __extends(BounceEase, _super);
  51628. function BounceEase(bounces, bounciness) {
  51629. if (bounces === void 0) { bounces = 3; }
  51630. if (bounciness === void 0) { bounciness = 2; }
  51631. var _this = _super.call(this) || this;
  51632. _this.bounces = bounces;
  51633. _this.bounciness = bounciness;
  51634. return _this;
  51635. }
  51636. BounceEase.prototype.easeInCore = function (gradient) {
  51637. var y = Math.max(0.0, this.bounces);
  51638. var bounciness = this.bounciness;
  51639. if (bounciness <= 1.0) {
  51640. bounciness = 1.001;
  51641. }
  51642. var num9 = Math.pow(bounciness, y);
  51643. var num5 = 1.0 - bounciness;
  51644. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51645. var num15 = gradient * num4;
  51646. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51647. var num3 = Math.floor(num65);
  51648. var num13 = num3 + 1.0;
  51649. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51650. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51651. var num7 = (num8 + num12) * 0.5;
  51652. var num6 = gradient - num7;
  51653. var num2 = num7 - num8;
  51654. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51655. };
  51656. return BounceEase;
  51657. }(EasingFunction));
  51658. BABYLON.BounceEase = BounceEase;
  51659. var CubicEase = /** @class */ (function (_super) {
  51660. __extends(CubicEase, _super);
  51661. function CubicEase() {
  51662. return _super !== null && _super.apply(this, arguments) || this;
  51663. }
  51664. CubicEase.prototype.easeInCore = function (gradient) {
  51665. return (gradient * gradient * gradient);
  51666. };
  51667. return CubicEase;
  51668. }(EasingFunction));
  51669. BABYLON.CubicEase = CubicEase;
  51670. var ElasticEase = /** @class */ (function (_super) {
  51671. __extends(ElasticEase, _super);
  51672. function ElasticEase(oscillations, springiness) {
  51673. if (oscillations === void 0) { oscillations = 3; }
  51674. if (springiness === void 0) { springiness = 3; }
  51675. var _this = _super.call(this) || this;
  51676. _this.oscillations = oscillations;
  51677. _this.springiness = springiness;
  51678. return _this;
  51679. }
  51680. ElasticEase.prototype.easeInCore = function (gradient) {
  51681. var num2;
  51682. var num3 = Math.max(0.0, this.oscillations);
  51683. var num = Math.max(0.0, this.springiness);
  51684. if (num == 0) {
  51685. num2 = gradient;
  51686. }
  51687. else {
  51688. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51689. }
  51690. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51691. };
  51692. return ElasticEase;
  51693. }(EasingFunction));
  51694. BABYLON.ElasticEase = ElasticEase;
  51695. var ExponentialEase = /** @class */ (function (_super) {
  51696. __extends(ExponentialEase, _super);
  51697. function ExponentialEase(exponent) {
  51698. if (exponent === void 0) { exponent = 2; }
  51699. var _this = _super.call(this) || this;
  51700. _this.exponent = exponent;
  51701. return _this;
  51702. }
  51703. ExponentialEase.prototype.easeInCore = function (gradient) {
  51704. if (this.exponent <= 0) {
  51705. return gradient;
  51706. }
  51707. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51708. };
  51709. return ExponentialEase;
  51710. }(EasingFunction));
  51711. BABYLON.ExponentialEase = ExponentialEase;
  51712. var PowerEase = /** @class */ (function (_super) {
  51713. __extends(PowerEase, _super);
  51714. function PowerEase(power) {
  51715. if (power === void 0) { power = 2; }
  51716. var _this = _super.call(this) || this;
  51717. _this.power = power;
  51718. return _this;
  51719. }
  51720. PowerEase.prototype.easeInCore = function (gradient) {
  51721. var y = Math.max(0.0, this.power);
  51722. return Math.pow(gradient, y);
  51723. };
  51724. return PowerEase;
  51725. }(EasingFunction));
  51726. BABYLON.PowerEase = PowerEase;
  51727. var QuadraticEase = /** @class */ (function (_super) {
  51728. __extends(QuadraticEase, _super);
  51729. function QuadraticEase() {
  51730. return _super !== null && _super.apply(this, arguments) || this;
  51731. }
  51732. QuadraticEase.prototype.easeInCore = function (gradient) {
  51733. return (gradient * gradient);
  51734. };
  51735. return QuadraticEase;
  51736. }(EasingFunction));
  51737. BABYLON.QuadraticEase = QuadraticEase;
  51738. var QuarticEase = /** @class */ (function (_super) {
  51739. __extends(QuarticEase, _super);
  51740. function QuarticEase() {
  51741. return _super !== null && _super.apply(this, arguments) || this;
  51742. }
  51743. QuarticEase.prototype.easeInCore = function (gradient) {
  51744. return (gradient * gradient * gradient * gradient);
  51745. };
  51746. return QuarticEase;
  51747. }(EasingFunction));
  51748. BABYLON.QuarticEase = QuarticEase;
  51749. var QuinticEase = /** @class */ (function (_super) {
  51750. __extends(QuinticEase, _super);
  51751. function QuinticEase() {
  51752. return _super !== null && _super.apply(this, arguments) || this;
  51753. }
  51754. QuinticEase.prototype.easeInCore = function (gradient) {
  51755. return (gradient * gradient * gradient * gradient * gradient);
  51756. };
  51757. return QuinticEase;
  51758. }(EasingFunction));
  51759. BABYLON.QuinticEase = QuinticEase;
  51760. var SineEase = /** @class */ (function (_super) {
  51761. __extends(SineEase, _super);
  51762. function SineEase() {
  51763. return _super !== null && _super.apply(this, arguments) || this;
  51764. }
  51765. SineEase.prototype.easeInCore = function (gradient) {
  51766. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51767. };
  51768. return SineEase;
  51769. }(EasingFunction));
  51770. BABYLON.SineEase = SineEase;
  51771. var BezierCurveEase = /** @class */ (function (_super) {
  51772. __extends(BezierCurveEase, _super);
  51773. function BezierCurveEase(x1, y1, x2, y2) {
  51774. if (x1 === void 0) { x1 = 0; }
  51775. if (y1 === void 0) { y1 = 0; }
  51776. if (x2 === void 0) { x2 = 1; }
  51777. if (y2 === void 0) { y2 = 1; }
  51778. var _this = _super.call(this) || this;
  51779. _this.x1 = x1;
  51780. _this.y1 = y1;
  51781. _this.x2 = x2;
  51782. _this.y2 = y2;
  51783. return _this;
  51784. }
  51785. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51786. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51787. };
  51788. return BezierCurveEase;
  51789. }(EasingFunction));
  51790. BABYLON.BezierCurveEase = BezierCurveEase;
  51791. })(BABYLON || (BABYLON = {}));
  51792. //# sourceMappingURL=babylon.easing.js.map
  51793. var BABYLON;
  51794. (function (BABYLON) {
  51795. /**
  51796. * A Condition applied to an Action
  51797. */
  51798. var Condition = /** @class */ (function () {
  51799. /**
  51800. * Creates a new Condition
  51801. * @param actionManager the manager of the action the condition is applied to
  51802. */
  51803. function Condition(actionManager) {
  51804. this._actionManager = actionManager;
  51805. }
  51806. /**
  51807. * Check if the current condition is valid
  51808. * @returns a boolean
  51809. */
  51810. Condition.prototype.isValid = function () {
  51811. return true;
  51812. };
  51813. /**
  51814. * Internal only
  51815. * @hidden
  51816. */
  51817. Condition.prototype._getProperty = function (propertyPath) {
  51818. return this._actionManager._getProperty(propertyPath);
  51819. };
  51820. /**
  51821. * Internal only
  51822. * @hidden
  51823. */
  51824. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51825. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51826. };
  51827. /**
  51828. * Serialize placeholder for child classes
  51829. * @returns the serialized object
  51830. */
  51831. Condition.prototype.serialize = function () {
  51832. };
  51833. /**
  51834. * Internal only
  51835. * @hidden
  51836. */
  51837. Condition.prototype._serialize = function (serializedCondition) {
  51838. return {
  51839. type: 2,
  51840. children: [],
  51841. name: serializedCondition.name,
  51842. properties: serializedCondition.properties
  51843. };
  51844. };
  51845. return Condition;
  51846. }());
  51847. BABYLON.Condition = Condition;
  51848. /**
  51849. * Defines specific conditional operators as extensions of Condition
  51850. */
  51851. var ValueCondition = /** @class */ (function (_super) {
  51852. __extends(ValueCondition, _super);
  51853. /**
  51854. * Creates a new ValueCondition
  51855. * @param actionManager manager for the action the condition applies to
  51856. * @param target for the action
  51857. * @param propertyPath path to specify the property of the target the conditional operator uses
  51858. * @param value the value compared by the conditional operator against the current value of the property
  51859. * @param operator the conditional operator, default ValueCondition.IsEqual
  51860. */
  51861. function ValueCondition(actionManager, target,
  51862. /** path to specify the property of the target the conditional operator uses */
  51863. propertyPath,
  51864. /** the value compared by the conditional operator against the current value of the property */
  51865. value,
  51866. /** the conditional operator, default ValueCondition.IsEqual */
  51867. operator) {
  51868. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51869. var _this = _super.call(this, actionManager) || this;
  51870. _this.propertyPath = propertyPath;
  51871. _this.value = value;
  51872. _this.operator = operator;
  51873. _this._target = target;
  51874. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51875. _this._property = _this._getProperty(_this.propertyPath);
  51876. return _this;
  51877. }
  51878. Object.defineProperty(ValueCondition, "IsEqual", {
  51879. /**
  51880. * returns the number for IsEqual
  51881. */
  51882. get: function () {
  51883. return ValueCondition._IsEqual;
  51884. },
  51885. enumerable: true,
  51886. configurable: true
  51887. });
  51888. Object.defineProperty(ValueCondition, "IsDifferent", {
  51889. /**
  51890. * Returns the number for IsDifferent
  51891. */
  51892. get: function () {
  51893. return ValueCondition._IsDifferent;
  51894. },
  51895. enumerable: true,
  51896. configurable: true
  51897. });
  51898. Object.defineProperty(ValueCondition, "IsGreater", {
  51899. /**
  51900. * Returns the number for IsGreater
  51901. */
  51902. get: function () {
  51903. return ValueCondition._IsGreater;
  51904. },
  51905. enumerable: true,
  51906. configurable: true
  51907. });
  51908. Object.defineProperty(ValueCondition, "IsLesser", {
  51909. /**
  51910. * Returns the number for IsLesser
  51911. */
  51912. get: function () {
  51913. return ValueCondition._IsLesser;
  51914. },
  51915. enumerable: true,
  51916. configurable: true
  51917. });
  51918. /**
  51919. * Compares the given value with the property value for the specified conditional operator
  51920. * @returns the result of the comparison
  51921. */
  51922. ValueCondition.prototype.isValid = function () {
  51923. switch (this.operator) {
  51924. case ValueCondition.IsGreater:
  51925. return this._effectiveTarget[this._property] > this.value;
  51926. case ValueCondition.IsLesser:
  51927. return this._effectiveTarget[this._property] < this.value;
  51928. case ValueCondition.IsEqual:
  51929. case ValueCondition.IsDifferent:
  51930. var check;
  51931. if (this.value.equals) {
  51932. check = this.value.equals(this._effectiveTarget[this._property]);
  51933. }
  51934. else {
  51935. check = this.value === this._effectiveTarget[this._property];
  51936. }
  51937. return this.operator === ValueCondition.IsEqual ? check : !check;
  51938. }
  51939. return false;
  51940. };
  51941. /**
  51942. * Serialize the ValueCondition into a JSON compatible object
  51943. * @returns serialization object
  51944. */
  51945. ValueCondition.prototype.serialize = function () {
  51946. return this._serialize({
  51947. name: "ValueCondition",
  51948. properties: [
  51949. BABYLON.Action._GetTargetProperty(this._target),
  51950. { name: "propertyPath", value: this.propertyPath },
  51951. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51952. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51953. ]
  51954. });
  51955. };
  51956. /**
  51957. * Gets the name of the conditional operator for the ValueCondition
  51958. * @param operator the conditional operator
  51959. * @returns the name
  51960. */
  51961. ValueCondition.GetOperatorName = function (operator) {
  51962. switch (operator) {
  51963. case ValueCondition._IsEqual: return "IsEqual";
  51964. case ValueCondition._IsDifferent: return "IsDifferent";
  51965. case ValueCondition._IsGreater: return "IsGreater";
  51966. case ValueCondition._IsLesser: return "IsLesser";
  51967. default: return "";
  51968. }
  51969. };
  51970. /**
  51971. * Internal only
  51972. * @hidden
  51973. */
  51974. ValueCondition._IsEqual = 0;
  51975. /**
  51976. * Internal only
  51977. * @hidden
  51978. */
  51979. ValueCondition._IsDifferent = 1;
  51980. /**
  51981. * Internal only
  51982. * @hidden
  51983. */
  51984. ValueCondition._IsGreater = 2;
  51985. /**
  51986. * Internal only
  51987. * @hidden
  51988. */
  51989. ValueCondition._IsLesser = 3;
  51990. return ValueCondition;
  51991. }(Condition));
  51992. BABYLON.ValueCondition = ValueCondition;
  51993. /**
  51994. * Defines a predicate condition as an extension of Condition
  51995. */
  51996. var PredicateCondition = /** @class */ (function (_super) {
  51997. __extends(PredicateCondition, _super);
  51998. /**
  51999. * Creates a new PredicateCondition
  52000. * @param actionManager manager for the action the condition applies to
  52001. * @param predicate defines the predicate function used to validate the condition
  52002. */
  52003. function PredicateCondition(actionManager,
  52004. /** defines the predicate function used to validate the condition */
  52005. predicate) {
  52006. var _this = _super.call(this, actionManager) || this;
  52007. _this.predicate = predicate;
  52008. return _this;
  52009. }
  52010. /**
  52011. * @returns the validity of the predicate condition
  52012. */
  52013. PredicateCondition.prototype.isValid = function () {
  52014. return this.predicate();
  52015. };
  52016. return PredicateCondition;
  52017. }(Condition));
  52018. BABYLON.PredicateCondition = PredicateCondition;
  52019. /**
  52020. * Defines a state condition as an extension of Condition
  52021. */
  52022. var StateCondition = /** @class */ (function (_super) {
  52023. __extends(StateCondition, _super);
  52024. /**
  52025. * Creates a new StateCondition
  52026. * @param actionManager manager for the action the condition applies to
  52027. * @param target of the condition
  52028. * @param value to compare with target state
  52029. */
  52030. function StateCondition(actionManager, target, value) {
  52031. var _this = _super.call(this, actionManager) || this;
  52032. _this.value = value;
  52033. _this._target = target;
  52034. return _this;
  52035. }
  52036. /**
  52037. * @returns the validity of the state
  52038. */
  52039. StateCondition.prototype.isValid = function () {
  52040. return this._target.state === this.value;
  52041. };
  52042. /**
  52043. * Serialize the StateCondition into a JSON compatible object
  52044. * @returns serialization object
  52045. */
  52046. StateCondition.prototype.serialize = function () {
  52047. return this._serialize({
  52048. name: "StateCondition",
  52049. properties: [
  52050. BABYLON.Action._GetTargetProperty(this._target),
  52051. { name: "value", value: this.value }
  52052. ]
  52053. });
  52054. };
  52055. return StateCondition;
  52056. }(Condition));
  52057. BABYLON.StateCondition = StateCondition;
  52058. })(BABYLON || (BABYLON = {}));
  52059. //# sourceMappingURL=babylon.condition.js.map
  52060. var BABYLON;
  52061. (function (BABYLON) {
  52062. /**
  52063. * The action to be carried out following a trigger
  52064. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52065. */
  52066. var Action = /** @class */ (function () {
  52067. /**
  52068. * Creates a new Action
  52069. * @param triggerOptions the trigger, with or without parameters, for the action
  52070. * @param condition an optional determinant of action
  52071. */
  52072. function Action(
  52073. /** the trigger, with or without parameters, for the action */
  52074. triggerOptions, condition) {
  52075. this.triggerOptions = triggerOptions;
  52076. /**
  52077. * An event triggered prior to action being executed.
  52078. */
  52079. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52080. if (triggerOptions.parameter) {
  52081. this.trigger = triggerOptions.trigger;
  52082. this._triggerParameter = triggerOptions.parameter;
  52083. }
  52084. else {
  52085. this.trigger = triggerOptions;
  52086. }
  52087. this._nextActiveAction = this;
  52088. this._condition = condition;
  52089. }
  52090. /**
  52091. * Internal only
  52092. * @hidden
  52093. */
  52094. Action.prototype._prepare = function () {
  52095. };
  52096. /**
  52097. * Gets the trigger parameters
  52098. * @returns the trigger parameters
  52099. */
  52100. Action.prototype.getTriggerParameter = function () {
  52101. return this._triggerParameter;
  52102. };
  52103. /**
  52104. * Internal only - executes current action event
  52105. * @hidden
  52106. */
  52107. Action.prototype._executeCurrent = function (evt) {
  52108. if (this._nextActiveAction._condition) {
  52109. var condition = this._nextActiveAction._condition;
  52110. var currentRenderId = this._actionManager.getScene().getRenderId();
  52111. // We cache the current evaluation for the current frame
  52112. if (condition._evaluationId === currentRenderId) {
  52113. if (!condition._currentResult) {
  52114. return;
  52115. }
  52116. }
  52117. else {
  52118. condition._evaluationId = currentRenderId;
  52119. if (!condition.isValid()) {
  52120. condition._currentResult = false;
  52121. return;
  52122. }
  52123. condition._currentResult = true;
  52124. }
  52125. }
  52126. this.onBeforeExecuteObservable.notifyObservers(this);
  52127. this._nextActiveAction.execute(evt);
  52128. this.skipToNextActiveAction();
  52129. };
  52130. /**
  52131. * Execute placeholder for child classes
  52132. * @param evt optional action event
  52133. */
  52134. Action.prototype.execute = function (evt) {
  52135. };
  52136. /**
  52137. * Skips to next active action
  52138. */
  52139. Action.prototype.skipToNextActiveAction = function () {
  52140. if (this._nextActiveAction._child) {
  52141. if (!this._nextActiveAction._child._actionManager) {
  52142. this._nextActiveAction._child._actionManager = this._actionManager;
  52143. }
  52144. this._nextActiveAction = this._nextActiveAction._child;
  52145. }
  52146. else {
  52147. this._nextActiveAction = this;
  52148. }
  52149. };
  52150. /**
  52151. * Adds action to chain of actions, may be a DoNothingAction
  52152. * @param action defines the next action to execute
  52153. * @returns The action passed in
  52154. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52155. */
  52156. Action.prototype.then = function (action) {
  52157. this._child = action;
  52158. action._actionManager = this._actionManager;
  52159. action._prepare();
  52160. return action;
  52161. };
  52162. /**
  52163. * Internal only
  52164. * @hidden
  52165. */
  52166. Action.prototype._getProperty = function (propertyPath) {
  52167. return this._actionManager._getProperty(propertyPath);
  52168. };
  52169. /**
  52170. * Internal only
  52171. * @hidden
  52172. */
  52173. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52174. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52175. };
  52176. /**
  52177. * Serialize placeholder for child classes
  52178. * @param parent of child
  52179. * @returns the serialized object
  52180. */
  52181. Action.prototype.serialize = function (parent) {
  52182. };
  52183. /**
  52184. * Internal only called by serialize
  52185. * @hidden
  52186. */
  52187. Action.prototype._serialize = function (serializedAction, parent) {
  52188. var serializationObject = {
  52189. type: 1,
  52190. children: [],
  52191. name: serializedAction.name,
  52192. properties: serializedAction.properties || []
  52193. };
  52194. // Serialize child
  52195. if (this._child) {
  52196. this._child.serialize(serializationObject);
  52197. }
  52198. // Check if "this" has a condition
  52199. if (this._condition) {
  52200. var serializedCondition = this._condition.serialize();
  52201. serializedCondition.children.push(serializationObject);
  52202. if (parent) {
  52203. parent.children.push(serializedCondition);
  52204. }
  52205. return serializedCondition;
  52206. }
  52207. if (parent) {
  52208. parent.children.push(serializationObject);
  52209. }
  52210. return serializationObject;
  52211. };
  52212. /**
  52213. * Internal only
  52214. * @hidden
  52215. */
  52216. Action._SerializeValueAsString = function (value) {
  52217. if (typeof value === "number") {
  52218. return value.toString();
  52219. }
  52220. if (typeof value === "boolean") {
  52221. return value ? "true" : "false";
  52222. }
  52223. if (value instanceof BABYLON.Vector2) {
  52224. return value.x + ", " + value.y;
  52225. }
  52226. if (value instanceof BABYLON.Vector3) {
  52227. return value.x + ", " + value.y + ", " + value.z;
  52228. }
  52229. if (value instanceof BABYLON.Color3) {
  52230. return value.r + ", " + value.g + ", " + value.b;
  52231. }
  52232. if (value instanceof BABYLON.Color4) {
  52233. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52234. }
  52235. return value; // string
  52236. };
  52237. /**
  52238. * Internal only
  52239. * @hidden
  52240. */
  52241. Action._GetTargetProperty = function (target) {
  52242. return {
  52243. name: "target",
  52244. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52245. : target instanceof BABYLON.Light ? "LightProperties"
  52246. : target instanceof BABYLON.Camera ? "CameraProperties"
  52247. : "SceneProperties",
  52248. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52249. };
  52250. };
  52251. return Action;
  52252. }());
  52253. BABYLON.Action = Action;
  52254. })(BABYLON || (BABYLON = {}));
  52255. //# sourceMappingURL=babylon.action.js.map
  52256. var BABYLON;
  52257. (function (BABYLON) {
  52258. /**
  52259. * ActionEvent is the event being sent when an action is triggered.
  52260. */
  52261. var ActionEvent = /** @class */ (function () {
  52262. /**
  52263. * Creates a new ActionEvent
  52264. * @param source The mesh or sprite that triggered the action
  52265. * @param pointerX The X mouse cursor position at the time of the event
  52266. * @param pointerY The Y mouse cursor position at the time of the event
  52267. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52268. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52269. * @param additionalData additional data for the event
  52270. */
  52271. function ActionEvent(
  52272. /** The mesh or sprite that triggered the action */
  52273. source,
  52274. /** The X mouse cursor position at the time of the event */
  52275. pointerX,
  52276. /** The Y mouse cursor position at the time of the event */
  52277. pointerY,
  52278. /** The mesh that is currently pointed at (can be null) */
  52279. meshUnderPointer,
  52280. /** the original (browser) event that triggered the ActionEvent */
  52281. sourceEvent,
  52282. /** additional data for the event */
  52283. additionalData) {
  52284. this.source = source;
  52285. this.pointerX = pointerX;
  52286. this.pointerY = pointerY;
  52287. this.meshUnderPointer = meshUnderPointer;
  52288. this.sourceEvent = sourceEvent;
  52289. this.additionalData = additionalData;
  52290. }
  52291. /**
  52292. * Helper function to auto-create an ActionEvent from a source mesh.
  52293. * @param source The source mesh that triggered the event
  52294. * @param evt The original (browser) event
  52295. * @param additionalData additional data for the event
  52296. * @returns the new ActionEvent
  52297. */
  52298. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52299. var scene = source.getScene();
  52300. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52301. };
  52302. /**
  52303. * Helper function to auto-create an ActionEvent from a source sprite
  52304. * @param source The source sprite that triggered the event
  52305. * @param scene Scene associated with the sprite
  52306. * @param evt The original (browser) event
  52307. * @param additionalData additional data for the event
  52308. * @returns the new ActionEvent
  52309. */
  52310. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52311. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52312. };
  52313. /**
  52314. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52315. * @param scene the scene where the event occurred
  52316. * @param evt The original (browser) event
  52317. * @returns the new ActionEvent
  52318. */
  52319. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52320. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52321. };
  52322. /**
  52323. * Helper function to auto-create an ActionEvent from a primitive
  52324. * @param prim defines the target primitive
  52325. * @param pointerPos defines the pointer position
  52326. * @param evt The original (browser) event
  52327. * @param additionalData additional data for the event
  52328. * @returns the new ActionEvent
  52329. */
  52330. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52331. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52332. };
  52333. return ActionEvent;
  52334. }());
  52335. BABYLON.ActionEvent = ActionEvent;
  52336. /**
  52337. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52338. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52339. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52340. */
  52341. var ActionManager = /** @class */ (function () {
  52342. /**
  52343. * Creates a new action manager
  52344. * @param scene defines the hosting scene
  52345. */
  52346. function ActionManager(scene) {
  52347. // Members
  52348. /** Gets the list of actions */
  52349. this.actions = new Array();
  52350. /** Gets the cursor to use when hovering items */
  52351. this.hoverCursor = '';
  52352. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52353. scene.actionManagers.push(this);
  52354. }
  52355. Object.defineProperty(ActionManager, "NothingTrigger", {
  52356. /**
  52357. * Nothing
  52358. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52359. */
  52360. get: function () {
  52361. return ActionManager._NothingTrigger;
  52362. },
  52363. enumerable: true,
  52364. configurable: true
  52365. });
  52366. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52367. /**
  52368. * On pick
  52369. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52370. */
  52371. get: function () {
  52372. return ActionManager._OnPickTrigger;
  52373. },
  52374. enumerable: true,
  52375. configurable: true
  52376. });
  52377. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52378. /**
  52379. * On left pick
  52380. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52381. */
  52382. get: function () {
  52383. return ActionManager._OnLeftPickTrigger;
  52384. },
  52385. enumerable: true,
  52386. configurable: true
  52387. });
  52388. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52389. /**
  52390. * On right pick
  52391. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52392. */
  52393. get: function () {
  52394. return ActionManager._OnRightPickTrigger;
  52395. },
  52396. enumerable: true,
  52397. configurable: true
  52398. });
  52399. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52400. /**
  52401. * On center pick
  52402. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52403. */
  52404. get: function () {
  52405. return ActionManager._OnCenterPickTrigger;
  52406. },
  52407. enumerable: true,
  52408. configurable: true
  52409. });
  52410. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52411. /**
  52412. * On pick down
  52413. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52414. */
  52415. get: function () {
  52416. return ActionManager._OnPickDownTrigger;
  52417. },
  52418. enumerable: true,
  52419. configurable: true
  52420. });
  52421. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52422. /**
  52423. * On double pick
  52424. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52425. */
  52426. get: function () {
  52427. return ActionManager._OnDoublePickTrigger;
  52428. },
  52429. enumerable: true,
  52430. configurable: true
  52431. });
  52432. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52433. /**
  52434. * On pick up
  52435. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52436. */
  52437. get: function () {
  52438. return ActionManager._OnPickUpTrigger;
  52439. },
  52440. enumerable: true,
  52441. configurable: true
  52442. });
  52443. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52444. /**
  52445. * On pick out.
  52446. * This trigger will only be raised if you also declared a OnPickDown
  52447. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52448. */
  52449. get: function () {
  52450. return ActionManager._OnPickOutTrigger;
  52451. },
  52452. enumerable: true,
  52453. configurable: true
  52454. });
  52455. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52456. /**
  52457. * On long press
  52458. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52459. */
  52460. get: function () {
  52461. return ActionManager._OnLongPressTrigger;
  52462. },
  52463. enumerable: true,
  52464. configurable: true
  52465. });
  52466. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52467. /**
  52468. * On pointer over
  52469. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52470. */
  52471. get: function () {
  52472. return ActionManager._OnPointerOverTrigger;
  52473. },
  52474. enumerable: true,
  52475. configurable: true
  52476. });
  52477. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52478. /**
  52479. * On pointer out
  52480. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52481. */
  52482. get: function () {
  52483. return ActionManager._OnPointerOutTrigger;
  52484. },
  52485. enumerable: true,
  52486. configurable: true
  52487. });
  52488. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52489. /**
  52490. * On every frame
  52491. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52492. */
  52493. get: function () {
  52494. return ActionManager._OnEveryFrameTrigger;
  52495. },
  52496. enumerable: true,
  52497. configurable: true
  52498. });
  52499. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52500. /**
  52501. * On intersection enter
  52502. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52503. */
  52504. get: function () {
  52505. return ActionManager._OnIntersectionEnterTrigger;
  52506. },
  52507. enumerable: true,
  52508. configurable: true
  52509. });
  52510. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52511. /**
  52512. * On intersection exit
  52513. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52514. */
  52515. get: function () {
  52516. return ActionManager._OnIntersectionExitTrigger;
  52517. },
  52518. enumerable: true,
  52519. configurable: true
  52520. });
  52521. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52522. /**
  52523. * On key down
  52524. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52525. */
  52526. get: function () {
  52527. return ActionManager._OnKeyDownTrigger;
  52528. },
  52529. enumerable: true,
  52530. configurable: true
  52531. });
  52532. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52533. /**
  52534. * On key up
  52535. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52536. */
  52537. get: function () {
  52538. return ActionManager._OnKeyUpTrigger;
  52539. },
  52540. enumerable: true,
  52541. configurable: true
  52542. });
  52543. // Methods
  52544. /**
  52545. * Releases all associated resources
  52546. */
  52547. ActionManager.prototype.dispose = function () {
  52548. var index = this._scene.actionManagers.indexOf(this);
  52549. for (var i = 0; i < this.actions.length; i++) {
  52550. var action = this.actions[i];
  52551. ActionManager.Triggers[action.trigger]--;
  52552. if (ActionManager.Triggers[action.trigger] === 0) {
  52553. delete ActionManager.Triggers[action.trigger];
  52554. }
  52555. }
  52556. if (index > -1) {
  52557. this._scene.actionManagers.splice(index, 1);
  52558. }
  52559. };
  52560. /**
  52561. * Gets hosting scene
  52562. * @returns the hosting scene
  52563. */
  52564. ActionManager.prototype.getScene = function () {
  52565. return this._scene;
  52566. };
  52567. /**
  52568. * Does this action manager handles actions of any of the given triggers
  52569. * @param triggers defines the triggers to be tested
  52570. * @return a boolean indicating whether one (or more) of the triggers is handled
  52571. */
  52572. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52573. for (var index = 0; index < this.actions.length; index++) {
  52574. var action = this.actions[index];
  52575. if (triggers.indexOf(action.trigger) > -1) {
  52576. return true;
  52577. }
  52578. }
  52579. return false;
  52580. };
  52581. /**
  52582. * Does this action manager handles actions of a given trigger
  52583. * @param trigger defines the trigger to be tested
  52584. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52585. * @return whether the trigger is handled
  52586. */
  52587. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52588. for (var index = 0; index < this.actions.length; index++) {
  52589. var action = this.actions[index];
  52590. if (action.trigger === trigger) {
  52591. if (parameterPredicate) {
  52592. if (parameterPredicate(action.getTriggerParameter())) {
  52593. return true;
  52594. }
  52595. }
  52596. else {
  52597. return true;
  52598. }
  52599. }
  52600. }
  52601. return false;
  52602. };
  52603. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52604. /**
  52605. * Does this action manager has pointer triggers
  52606. */
  52607. get: function () {
  52608. for (var index = 0; index < this.actions.length; index++) {
  52609. var action = this.actions[index];
  52610. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52611. return true;
  52612. }
  52613. }
  52614. return false;
  52615. },
  52616. enumerable: true,
  52617. configurable: true
  52618. });
  52619. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52620. /**
  52621. * Does this action manager has pick triggers
  52622. */
  52623. get: function () {
  52624. for (var index = 0; index < this.actions.length; index++) {
  52625. var action = this.actions[index];
  52626. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52627. return true;
  52628. }
  52629. }
  52630. return false;
  52631. },
  52632. enumerable: true,
  52633. configurable: true
  52634. });
  52635. Object.defineProperty(ActionManager, "HasTriggers", {
  52636. /**
  52637. * Does exist one action manager with at least one trigger
  52638. **/
  52639. get: function () {
  52640. for (var t in ActionManager.Triggers) {
  52641. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52642. return true;
  52643. }
  52644. }
  52645. return false;
  52646. },
  52647. enumerable: true,
  52648. configurable: true
  52649. });
  52650. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52651. /**
  52652. * Does exist one action manager with at least one pick trigger
  52653. **/
  52654. get: function () {
  52655. for (var t in ActionManager.Triggers) {
  52656. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52657. var t_int = parseInt(t);
  52658. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52659. return true;
  52660. }
  52661. }
  52662. }
  52663. return false;
  52664. },
  52665. enumerable: true,
  52666. configurable: true
  52667. });
  52668. /**
  52669. * Does exist one action manager that handles actions of a given trigger
  52670. * @param trigger defines the trigger to be tested
  52671. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52672. **/
  52673. ActionManager.HasSpecificTrigger = function (trigger) {
  52674. for (var t in ActionManager.Triggers) {
  52675. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52676. var t_int = parseInt(t);
  52677. if (t_int === trigger) {
  52678. return true;
  52679. }
  52680. }
  52681. }
  52682. return false;
  52683. };
  52684. /**
  52685. * Registers an action to this action manager
  52686. * @param action defines the action to be registered
  52687. * @return the action amended (prepared) after registration
  52688. */
  52689. ActionManager.prototype.registerAction = function (action) {
  52690. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52691. if (this.getScene().actionManager !== this) {
  52692. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52693. return null;
  52694. }
  52695. }
  52696. this.actions.push(action);
  52697. if (ActionManager.Triggers[action.trigger]) {
  52698. ActionManager.Triggers[action.trigger]++;
  52699. }
  52700. else {
  52701. ActionManager.Triggers[action.trigger] = 1;
  52702. }
  52703. action._actionManager = this;
  52704. action._prepare();
  52705. return action;
  52706. };
  52707. /**
  52708. * Unregisters an action to this action manager
  52709. * @param action defines the action to be unregistered
  52710. * @return a boolean indicating whether the action has been unregistered
  52711. */
  52712. ActionManager.prototype.unregisterAction = function (action) {
  52713. var index = this.actions.indexOf(action);
  52714. if (index !== -1) {
  52715. this.actions.splice(index, 1);
  52716. ActionManager.Triggers[action.trigger] -= 1;
  52717. if (ActionManager.Triggers[action.trigger] === 0) {
  52718. delete ActionManager.Triggers[action.trigger];
  52719. }
  52720. delete action._actionManager;
  52721. return true;
  52722. }
  52723. return false;
  52724. };
  52725. /**
  52726. * Process a specific trigger
  52727. * @param trigger defines the trigger to process
  52728. * @param evt defines the event details to be processed
  52729. */
  52730. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52731. for (var index = 0; index < this.actions.length; index++) {
  52732. var action = this.actions[index];
  52733. if (action.trigger === trigger) {
  52734. if (evt) {
  52735. if (trigger === ActionManager.OnKeyUpTrigger
  52736. || trigger === ActionManager.OnKeyDownTrigger) {
  52737. var parameter = action.getTriggerParameter();
  52738. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52739. if (!parameter.toLowerCase) {
  52740. continue;
  52741. }
  52742. var lowerCase = parameter.toLowerCase();
  52743. if (lowerCase !== evt.sourceEvent.key) {
  52744. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52745. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52746. if (actualkey !== lowerCase) {
  52747. continue;
  52748. }
  52749. }
  52750. }
  52751. }
  52752. }
  52753. action._executeCurrent(evt);
  52754. }
  52755. }
  52756. };
  52757. /** @hidden */
  52758. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52759. var properties = propertyPath.split(".");
  52760. for (var index = 0; index < properties.length - 1; index++) {
  52761. target = target[properties[index]];
  52762. }
  52763. return target;
  52764. };
  52765. /** @hidden */
  52766. ActionManager.prototype._getProperty = function (propertyPath) {
  52767. var properties = propertyPath.split(".");
  52768. return properties[properties.length - 1];
  52769. };
  52770. /**
  52771. * Serialize this manager to a JSON object
  52772. * @param name defines the property name to store this manager
  52773. * @returns a JSON representation of this manager
  52774. */
  52775. ActionManager.prototype.serialize = function (name) {
  52776. var root = {
  52777. children: new Array(),
  52778. name: name,
  52779. type: 3,
  52780. properties: new Array() // Empty for root but required
  52781. };
  52782. for (var i = 0; i < this.actions.length; i++) {
  52783. var triggerObject = {
  52784. type: 0,
  52785. children: new Array(),
  52786. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52787. properties: new Array()
  52788. };
  52789. var triggerOptions = this.actions[i].triggerOptions;
  52790. if (triggerOptions && typeof triggerOptions !== "number") {
  52791. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52792. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52793. }
  52794. else {
  52795. var parameter = {};
  52796. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52797. if (triggerOptions.parameter.mesh) {
  52798. parameter._meshId = triggerOptions.parameter.mesh.id;
  52799. }
  52800. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52801. }
  52802. }
  52803. // Serialize child action, recursively
  52804. this.actions[i].serialize(triggerObject);
  52805. // Add serialized trigger
  52806. root.children.push(triggerObject);
  52807. }
  52808. return root;
  52809. };
  52810. /**
  52811. * Creates a new ActionManager from a JSON data
  52812. * @param parsedActions defines the JSON data to read from
  52813. * @param object defines the hosting mesh
  52814. * @param scene defines the hosting scene
  52815. */
  52816. ActionManager.Parse = function (parsedActions, object, scene) {
  52817. var actionManager = new ActionManager(scene);
  52818. if (object === null)
  52819. scene.actionManager = actionManager;
  52820. else
  52821. object.actionManager = actionManager;
  52822. // instanciate a new object
  52823. var instanciate = function (name, params) {
  52824. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52825. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52826. newInstance.constructor.apply(newInstance, params);
  52827. return newInstance;
  52828. };
  52829. var parseParameter = function (name, value, target, propertyPath) {
  52830. if (propertyPath === null) {
  52831. // String, boolean or float
  52832. var floatValue = parseFloat(value);
  52833. if (value === "true" || value === "false")
  52834. return value === "true";
  52835. else
  52836. return isNaN(floatValue) ? value : floatValue;
  52837. }
  52838. var effectiveTarget = propertyPath.split(".");
  52839. var values = value.split(",");
  52840. // Get effective Target
  52841. for (var i = 0; i < effectiveTarget.length; i++) {
  52842. target = target[effectiveTarget[i]];
  52843. }
  52844. // Return appropriate value with its type
  52845. if (typeof (target) === "boolean")
  52846. return values[0] === "true";
  52847. if (typeof (target) === "string")
  52848. return values[0];
  52849. // Parameters with multiple values such as Vector3 etc.
  52850. var split = new Array();
  52851. for (var i = 0; i < values.length; i++)
  52852. split.push(parseFloat(values[i]));
  52853. if (target instanceof BABYLON.Vector3)
  52854. return BABYLON.Vector3.FromArray(split);
  52855. if (target instanceof BABYLON.Vector4)
  52856. return BABYLON.Vector4.FromArray(split);
  52857. if (target instanceof BABYLON.Color3)
  52858. return BABYLON.Color3.FromArray(split);
  52859. if (target instanceof BABYLON.Color4)
  52860. return BABYLON.Color4.FromArray(split);
  52861. return parseFloat(values[0]);
  52862. };
  52863. // traverse graph per trigger
  52864. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52865. if (combineArray === void 0) { combineArray = null; }
  52866. if (parsedAction.detached)
  52867. return;
  52868. var parameters = new Array();
  52869. var target = null;
  52870. var propertyPath = null;
  52871. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52872. // Parameters
  52873. if (parsedAction.type === 2)
  52874. parameters.push(actionManager);
  52875. else
  52876. parameters.push(trigger);
  52877. if (combine) {
  52878. var actions = new Array();
  52879. for (var j = 0; j < parsedAction.combine.length; j++) {
  52880. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52881. }
  52882. parameters.push(actions);
  52883. }
  52884. else {
  52885. for (var i = 0; i < parsedAction.properties.length; i++) {
  52886. var value = parsedAction.properties[i].value;
  52887. var name = parsedAction.properties[i].name;
  52888. var targetType = parsedAction.properties[i].targetType;
  52889. if (name === "target")
  52890. if (targetType !== null && targetType === "SceneProperties")
  52891. value = target = scene;
  52892. else
  52893. value = target = scene.getNodeByName(value);
  52894. else if (name === "parent")
  52895. value = scene.getNodeByName(value);
  52896. else if (name === "sound")
  52897. value = scene.getSoundByName(value);
  52898. else if (name !== "propertyPath") {
  52899. if (parsedAction.type === 2 && name === "operator")
  52900. value = BABYLON.ValueCondition[value];
  52901. else
  52902. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52903. }
  52904. else {
  52905. propertyPath = value;
  52906. }
  52907. parameters.push(value);
  52908. }
  52909. }
  52910. if (combineArray === null) {
  52911. parameters.push(condition);
  52912. }
  52913. else {
  52914. parameters.push(null);
  52915. }
  52916. // If interpolate value action
  52917. if (parsedAction.name === "InterpolateValueAction") {
  52918. var param = parameters[parameters.length - 2];
  52919. parameters[parameters.length - 1] = param;
  52920. parameters[parameters.length - 2] = condition;
  52921. }
  52922. // Action or condition(s) and not CombineAction
  52923. var newAction = instanciate(parsedAction.name, parameters);
  52924. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52925. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52926. if (action)
  52927. action.then(nothing);
  52928. else
  52929. actionManager.registerAction(nothing);
  52930. action = nothing;
  52931. }
  52932. if (combineArray === null) {
  52933. if (newAction instanceof BABYLON.Condition) {
  52934. condition = newAction;
  52935. newAction = action;
  52936. }
  52937. else {
  52938. condition = null;
  52939. if (action)
  52940. action.then(newAction);
  52941. else
  52942. actionManager.registerAction(newAction);
  52943. }
  52944. }
  52945. else {
  52946. combineArray.push(newAction);
  52947. }
  52948. for (var i = 0; i < parsedAction.children.length; i++)
  52949. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52950. };
  52951. // triggers
  52952. for (var i = 0; i < parsedActions.children.length; i++) {
  52953. var triggerParams;
  52954. var trigger = parsedActions.children[i];
  52955. if (trigger.properties.length > 0) {
  52956. var param = trigger.properties[0].value;
  52957. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52958. if (value._meshId) {
  52959. value.mesh = scene.getMeshByID(value._meshId);
  52960. }
  52961. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52962. }
  52963. else
  52964. triggerParams = ActionManager[trigger.name];
  52965. for (var j = 0; j < trigger.children.length; j++) {
  52966. if (!trigger.detached)
  52967. traverse(trigger.children[j], triggerParams, null, null);
  52968. }
  52969. }
  52970. };
  52971. /**
  52972. * Get a trigger name by index
  52973. * @param trigger defines the trigger index
  52974. * @returns a trigger name
  52975. */
  52976. ActionManager.GetTriggerName = function (trigger) {
  52977. switch (trigger) {
  52978. case 0: return "NothingTrigger";
  52979. case 1: return "OnPickTrigger";
  52980. case 2: return "OnLeftPickTrigger";
  52981. case 3: return "OnRightPickTrigger";
  52982. case 4: return "OnCenterPickTrigger";
  52983. case 5: return "OnPickDownTrigger";
  52984. case 6: return "OnPickUpTrigger";
  52985. case 7: return "OnLongPressTrigger";
  52986. case 8: return "OnPointerOverTrigger";
  52987. case 9: return "OnPointerOutTrigger";
  52988. case 10: return "OnEveryFrameTrigger";
  52989. case 11: return "OnIntersectionEnterTrigger";
  52990. case 12: return "OnIntersectionExitTrigger";
  52991. case 13: return "OnKeyDownTrigger";
  52992. case 14: return "OnKeyUpTrigger";
  52993. case 15: return "OnPickOutTrigger";
  52994. default: return "";
  52995. }
  52996. };
  52997. // Statics
  52998. ActionManager._NothingTrigger = 0;
  52999. ActionManager._OnPickTrigger = 1;
  53000. ActionManager._OnLeftPickTrigger = 2;
  53001. ActionManager._OnRightPickTrigger = 3;
  53002. ActionManager._OnCenterPickTrigger = 4;
  53003. ActionManager._OnPickDownTrigger = 5;
  53004. ActionManager._OnDoublePickTrigger = 6;
  53005. ActionManager._OnPickUpTrigger = 7;
  53006. ActionManager._OnLongPressTrigger = 8;
  53007. ActionManager._OnPointerOverTrigger = 9;
  53008. ActionManager._OnPointerOutTrigger = 10;
  53009. ActionManager._OnEveryFrameTrigger = 11;
  53010. ActionManager._OnIntersectionEnterTrigger = 12;
  53011. ActionManager._OnIntersectionExitTrigger = 13;
  53012. ActionManager._OnKeyDownTrigger = 14;
  53013. ActionManager._OnKeyUpTrigger = 15;
  53014. ActionManager._OnPickOutTrigger = 16;
  53015. /** Gets the list of active triggers */
  53016. ActionManager.Triggers = {};
  53017. return ActionManager;
  53018. }());
  53019. BABYLON.ActionManager = ActionManager;
  53020. })(BABYLON || (BABYLON = {}));
  53021. //# sourceMappingURL=babylon.actionManager.js.map
  53022. var BABYLON;
  53023. (function (BABYLON) {
  53024. var InterpolateValueAction = /** @class */ (function (_super) {
  53025. __extends(InterpolateValueAction, _super);
  53026. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53027. if (duration === void 0) { duration = 1000; }
  53028. var _this = _super.call(this, triggerOptions, condition) || this;
  53029. _this.propertyPath = propertyPath;
  53030. _this.value = value;
  53031. _this.duration = duration;
  53032. _this.stopOtherAnimations = stopOtherAnimations;
  53033. _this.onInterpolationDone = onInterpolationDone;
  53034. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53035. _this._target = _this._effectiveTarget = target;
  53036. return _this;
  53037. }
  53038. InterpolateValueAction.prototype._prepare = function () {
  53039. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53040. this._property = this._getProperty(this.propertyPath);
  53041. };
  53042. InterpolateValueAction.prototype.execute = function () {
  53043. var _this = this;
  53044. var scene = this._actionManager.getScene();
  53045. var keys = [
  53046. {
  53047. frame: 0,
  53048. value: this._effectiveTarget[this._property]
  53049. }, {
  53050. frame: 100,
  53051. value: this.value
  53052. }
  53053. ];
  53054. var dataType;
  53055. if (typeof this.value === "number") {
  53056. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53057. }
  53058. else if (this.value instanceof BABYLON.Color3) {
  53059. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53060. }
  53061. else if (this.value instanceof BABYLON.Vector3) {
  53062. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53063. }
  53064. else if (this.value instanceof BABYLON.Matrix) {
  53065. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53066. }
  53067. else if (this.value instanceof BABYLON.Quaternion) {
  53068. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53069. }
  53070. else {
  53071. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53072. return;
  53073. }
  53074. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53075. animation.setKeys(keys);
  53076. if (this.stopOtherAnimations) {
  53077. scene.stopAnimation(this._effectiveTarget);
  53078. }
  53079. var wrapper = function () {
  53080. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53081. if (_this.onInterpolationDone) {
  53082. _this.onInterpolationDone();
  53083. }
  53084. };
  53085. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53086. };
  53087. InterpolateValueAction.prototype.serialize = function (parent) {
  53088. return _super.prototype._serialize.call(this, {
  53089. name: "InterpolateValueAction",
  53090. properties: [
  53091. BABYLON.Action._GetTargetProperty(this._target),
  53092. { name: "propertyPath", value: this.propertyPath },
  53093. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53094. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53095. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53096. ]
  53097. }, parent);
  53098. };
  53099. return InterpolateValueAction;
  53100. }(BABYLON.Action));
  53101. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53102. })(BABYLON || (BABYLON = {}));
  53103. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53104. var BABYLON;
  53105. (function (BABYLON) {
  53106. var SwitchBooleanAction = /** @class */ (function (_super) {
  53107. __extends(SwitchBooleanAction, _super);
  53108. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53109. var _this = _super.call(this, triggerOptions, condition) || this;
  53110. _this.propertyPath = propertyPath;
  53111. _this._target = _this._effectiveTarget = target;
  53112. return _this;
  53113. }
  53114. SwitchBooleanAction.prototype._prepare = function () {
  53115. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53116. this._property = this._getProperty(this.propertyPath);
  53117. };
  53118. SwitchBooleanAction.prototype.execute = function () {
  53119. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53120. };
  53121. SwitchBooleanAction.prototype.serialize = function (parent) {
  53122. return _super.prototype._serialize.call(this, {
  53123. name: "SwitchBooleanAction",
  53124. properties: [
  53125. BABYLON.Action._GetTargetProperty(this._target),
  53126. { name: "propertyPath", value: this.propertyPath }
  53127. ]
  53128. }, parent);
  53129. };
  53130. return SwitchBooleanAction;
  53131. }(BABYLON.Action));
  53132. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53133. var SetStateAction = /** @class */ (function (_super) {
  53134. __extends(SetStateAction, _super);
  53135. function SetStateAction(triggerOptions, target, value, condition) {
  53136. var _this = _super.call(this, triggerOptions, condition) || this;
  53137. _this.value = value;
  53138. _this._target = target;
  53139. return _this;
  53140. }
  53141. SetStateAction.prototype.execute = function () {
  53142. this._target.state = this.value;
  53143. };
  53144. SetStateAction.prototype.serialize = function (parent) {
  53145. return _super.prototype._serialize.call(this, {
  53146. name: "SetStateAction",
  53147. properties: [
  53148. BABYLON.Action._GetTargetProperty(this._target),
  53149. { name: "value", value: this.value }
  53150. ]
  53151. }, parent);
  53152. };
  53153. return SetStateAction;
  53154. }(BABYLON.Action));
  53155. BABYLON.SetStateAction = SetStateAction;
  53156. var SetValueAction = /** @class */ (function (_super) {
  53157. __extends(SetValueAction, _super);
  53158. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53159. var _this = _super.call(this, triggerOptions, condition) || this;
  53160. _this.propertyPath = propertyPath;
  53161. _this.value = value;
  53162. _this._target = _this._effectiveTarget = target;
  53163. return _this;
  53164. }
  53165. SetValueAction.prototype._prepare = function () {
  53166. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53167. this._property = this._getProperty(this.propertyPath);
  53168. };
  53169. SetValueAction.prototype.execute = function () {
  53170. this._effectiveTarget[this._property] = this.value;
  53171. if (this._target.markAsDirty) {
  53172. this._target.markAsDirty(this._property);
  53173. }
  53174. };
  53175. SetValueAction.prototype.serialize = function (parent) {
  53176. return _super.prototype._serialize.call(this, {
  53177. name: "SetValueAction",
  53178. properties: [
  53179. BABYLON.Action._GetTargetProperty(this._target),
  53180. { name: "propertyPath", value: this.propertyPath },
  53181. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53182. ]
  53183. }, parent);
  53184. };
  53185. return SetValueAction;
  53186. }(BABYLON.Action));
  53187. BABYLON.SetValueAction = SetValueAction;
  53188. var IncrementValueAction = /** @class */ (function (_super) {
  53189. __extends(IncrementValueAction, _super);
  53190. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53191. var _this = _super.call(this, triggerOptions, condition) || this;
  53192. _this.propertyPath = propertyPath;
  53193. _this.value = value;
  53194. _this._target = _this._effectiveTarget = target;
  53195. return _this;
  53196. }
  53197. IncrementValueAction.prototype._prepare = function () {
  53198. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53199. this._property = this._getProperty(this.propertyPath);
  53200. if (typeof this._effectiveTarget[this._property] !== "number") {
  53201. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53202. }
  53203. };
  53204. IncrementValueAction.prototype.execute = function () {
  53205. this._effectiveTarget[this._property] += this.value;
  53206. if (this._target.markAsDirty) {
  53207. this._target.markAsDirty(this._property);
  53208. }
  53209. };
  53210. IncrementValueAction.prototype.serialize = function (parent) {
  53211. return _super.prototype._serialize.call(this, {
  53212. name: "IncrementValueAction",
  53213. properties: [
  53214. BABYLON.Action._GetTargetProperty(this._target),
  53215. { name: "propertyPath", value: this.propertyPath },
  53216. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53217. ]
  53218. }, parent);
  53219. };
  53220. return IncrementValueAction;
  53221. }(BABYLON.Action));
  53222. BABYLON.IncrementValueAction = IncrementValueAction;
  53223. var PlayAnimationAction = /** @class */ (function (_super) {
  53224. __extends(PlayAnimationAction, _super);
  53225. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53226. var _this = _super.call(this, triggerOptions, condition) || this;
  53227. _this.from = from;
  53228. _this.to = to;
  53229. _this.loop = loop;
  53230. _this._target = target;
  53231. return _this;
  53232. }
  53233. PlayAnimationAction.prototype._prepare = function () {
  53234. };
  53235. PlayAnimationAction.prototype.execute = function () {
  53236. var scene = this._actionManager.getScene();
  53237. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53238. };
  53239. PlayAnimationAction.prototype.serialize = function (parent) {
  53240. return _super.prototype._serialize.call(this, {
  53241. name: "PlayAnimationAction",
  53242. properties: [
  53243. BABYLON.Action._GetTargetProperty(this._target),
  53244. { name: "from", value: String(this.from) },
  53245. { name: "to", value: String(this.to) },
  53246. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53247. ]
  53248. }, parent);
  53249. };
  53250. return PlayAnimationAction;
  53251. }(BABYLON.Action));
  53252. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53253. var StopAnimationAction = /** @class */ (function (_super) {
  53254. __extends(StopAnimationAction, _super);
  53255. function StopAnimationAction(triggerOptions, target, condition) {
  53256. var _this = _super.call(this, triggerOptions, condition) || this;
  53257. _this._target = target;
  53258. return _this;
  53259. }
  53260. StopAnimationAction.prototype._prepare = function () {
  53261. };
  53262. StopAnimationAction.prototype.execute = function () {
  53263. var scene = this._actionManager.getScene();
  53264. scene.stopAnimation(this._target);
  53265. };
  53266. StopAnimationAction.prototype.serialize = function (parent) {
  53267. return _super.prototype._serialize.call(this, {
  53268. name: "StopAnimationAction",
  53269. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53270. }, parent);
  53271. };
  53272. return StopAnimationAction;
  53273. }(BABYLON.Action));
  53274. BABYLON.StopAnimationAction = StopAnimationAction;
  53275. var DoNothingAction = /** @class */ (function (_super) {
  53276. __extends(DoNothingAction, _super);
  53277. function DoNothingAction(triggerOptions, condition) {
  53278. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53279. return _super.call(this, triggerOptions, condition) || this;
  53280. }
  53281. DoNothingAction.prototype.execute = function () {
  53282. };
  53283. DoNothingAction.prototype.serialize = function (parent) {
  53284. return _super.prototype._serialize.call(this, {
  53285. name: "DoNothingAction",
  53286. properties: []
  53287. }, parent);
  53288. };
  53289. return DoNothingAction;
  53290. }(BABYLON.Action));
  53291. BABYLON.DoNothingAction = DoNothingAction;
  53292. var CombineAction = /** @class */ (function (_super) {
  53293. __extends(CombineAction, _super);
  53294. function CombineAction(triggerOptions, children, condition) {
  53295. var _this = _super.call(this, triggerOptions, condition) || this;
  53296. _this.children = children;
  53297. return _this;
  53298. }
  53299. CombineAction.prototype._prepare = function () {
  53300. for (var index = 0; index < this.children.length; index++) {
  53301. this.children[index]._actionManager = this._actionManager;
  53302. this.children[index]._prepare();
  53303. }
  53304. };
  53305. CombineAction.prototype.execute = function (evt) {
  53306. for (var index = 0; index < this.children.length; index++) {
  53307. this.children[index].execute(evt);
  53308. }
  53309. };
  53310. CombineAction.prototype.serialize = function (parent) {
  53311. var serializationObject = _super.prototype._serialize.call(this, {
  53312. name: "CombineAction",
  53313. properties: [],
  53314. combine: []
  53315. }, parent);
  53316. for (var i = 0; i < this.children.length; i++) {
  53317. serializationObject.combine.push(this.children[i].serialize(null));
  53318. }
  53319. return serializationObject;
  53320. };
  53321. return CombineAction;
  53322. }(BABYLON.Action));
  53323. BABYLON.CombineAction = CombineAction;
  53324. var ExecuteCodeAction = /** @class */ (function (_super) {
  53325. __extends(ExecuteCodeAction, _super);
  53326. function ExecuteCodeAction(triggerOptions, func, condition) {
  53327. var _this = _super.call(this, triggerOptions, condition) || this;
  53328. _this.func = func;
  53329. return _this;
  53330. }
  53331. ExecuteCodeAction.prototype.execute = function (evt) {
  53332. this.func(evt);
  53333. };
  53334. return ExecuteCodeAction;
  53335. }(BABYLON.Action));
  53336. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53337. var SetParentAction = /** @class */ (function (_super) {
  53338. __extends(SetParentAction, _super);
  53339. function SetParentAction(triggerOptions, target, parent, condition) {
  53340. var _this = _super.call(this, triggerOptions, condition) || this;
  53341. _this._target = target;
  53342. _this._parent = parent;
  53343. return _this;
  53344. }
  53345. SetParentAction.prototype._prepare = function () {
  53346. };
  53347. SetParentAction.prototype.execute = function () {
  53348. if (this._target.parent === this._parent) {
  53349. return;
  53350. }
  53351. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53352. invertParentWorldMatrix.invert();
  53353. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53354. this._target.parent = this._parent;
  53355. };
  53356. SetParentAction.prototype.serialize = function (parent) {
  53357. return _super.prototype._serialize.call(this, {
  53358. name: "SetParentAction",
  53359. properties: [
  53360. BABYLON.Action._GetTargetProperty(this._target),
  53361. BABYLON.Action._GetTargetProperty(this._parent),
  53362. ]
  53363. }, parent);
  53364. };
  53365. return SetParentAction;
  53366. }(BABYLON.Action));
  53367. BABYLON.SetParentAction = SetParentAction;
  53368. var PlaySoundAction = /** @class */ (function (_super) {
  53369. __extends(PlaySoundAction, _super);
  53370. function PlaySoundAction(triggerOptions, sound, condition) {
  53371. var _this = _super.call(this, triggerOptions, condition) || this;
  53372. _this._sound = sound;
  53373. return _this;
  53374. }
  53375. PlaySoundAction.prototype._prepare = function () {
  53376. };
  53377. PlaySoundAction.prototype.execute = function () {
  53378. if (this._sound !== undefined)
  53379. this._sound.play();
  53380. };
  53381. PlaySoundAction.prototype.serialize = function (parent) {
  53382. return _super.prototype._serialize.call(this, {
  53383. name: "PlaySoundAction",
  53384. properties: [{ name: "sound", value: this._sound.name }]
  53385. }, parent);
  53386. };
  53387. return PlaySoundAction;
  53388. }(BABYLON.Action));
  53389. BABYLON.PlaySoundAction = PlaySoundAction;
  53390. var StopSoundAction = /** @class */ (function (_super) {
  53391. __extends(StopSoundAction, _super);
  53392. function StopSoundAction(triggerOptions, sound, condition) {
  53393. var _this = _super.call(this, triggerOptions, condition) || this;
  53394. _this._sound = sound;
  53395. return _this;
  53396. }
  53397. StopSoundAction.prototype._prepare = function () {
  53398. };
  53399. StopSoundAction.prototype.execute = function () {
  53400. if (this._sound !== undefined)
  53401. this._sound.stop();
  53402. };
  53403. StopSoundAction.prototype.serialize = function (parent) {
  53404. return _super.prototype._serialize.call(this, {
  53405. name: "StopSoundAction",
  53406. properties: [{ name: "sound", value: this._sound.name }]
  53407. }, parent);
  53408. };
  53409. return StopSoundAction;
  53410. }(BABYLON.Action));
  53411. BABYLON.StopSoundAction = StopSoundAction;
  53412. })(BABYLON || (BABYLON = {}));
  53413. //# sourceMappingURL=babylon.directActions.js.map
  53414. var BABYLON;
  53415. (function (BABYLON) {
  53416. var SpriteManager = /** @class */ (function () {
  53417. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53418. if (epsilon === void 0) { epsilon = 0.01; }
  53419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53420. this.name = name;
  53421. this.sprites = new Array();
  53422. this.renderingGroupId = 0;
  53423. this.layerMask = 0x0FFFFFFF;
  53424. this.fogEnabled = true;
  53425. this.isPickable = false;
  53426. /**
  53427. * An event triggered when the manager is disposed.
  53428. */
  53429. this.onDisposeObservable = new BABYLON.Observable();
  53430. this._vertexBuffers = {};
  53431. this._capacity = capacity;
  53432. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53433. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53434. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53435. if (cellSize.width && cellSize.height) {
  53436. this.cellWidth = cellSize.width;
  53437. this.cellHeight = cellSize.height;
  53438. }
  53439. else if (cellSize !== undefined) {
  53440. this.cellWidth = cellSize;
  53441. this.cellHeight = cellSize;
  53442. }
  53443. else {
  53444. return;
  53445. }
  53446. this._epsilon = epsilon;
  53447. this._scene = scene;
  53448. this._scene.spriteManagers.push(this);
  53449. var indices = [];
  53450. var index = 0;
  53451. for (var count = 0; count < capacity; count++) {
  53452. indices.push(index);
  53453. indices.push(index + 1);
  53454. indices.push(index + 2);
  53455. indices.push(index);
  53456. indices.push(index + 2);
  53457. indices.push(index + 3);
  53458. index += 4;
  53459. }
  53460. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53461. // VBO
  53462. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53463. this._vertexData = new Float32Array(capacity * 16 * 4);
  53464. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53465. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53466. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53467. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53468. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53469. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53470. this._vertexBuffers["options"] = options;
  53471. this._vertexBuffers["cellInfo"] = cellInfo;
  53472. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53473. // Effects
  53474. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53475. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53476. }
  53477. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53478. set: function (callback) {
  53479. if (this._onDisposeObserver) {
  53480. this.onDisposeObservable.remove(this._onDisposeObserver);
  53481. }
  53482. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53483. },
  53484. enumerable: true,
  53485. configurable: true
  53486. });
  53487. Object.defineProperty(SpriteManager.prototype, "texture", {
  53488. get: function () {
  53489. return this._spriteTexture;
  53490. },
  53491. set: function (value) {
  53492. this._spriteTexture = value;
  53493. },
  53494. enumerable: true,
  53495. configurable: true
  53496. });
  53497. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53498. var arrayOffset = index * 16;
  53499. if (offsetX === 0)
  53500. offsetX = this._epsilon;
  53501. else if (offsetX === 1)
  53502. offsetX = 1 - this._epsilon;
  53503. if (offsetY === 0)
  53504. offsetY = this._epsilon;
  53505. else if (offsetY === 1)
  53506. offsetY = 1 - this._epsilon;
  53507. this._vertexData[arrayOffset] = sprite.position.x;
  53508. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53509. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53510. this._vertexData[arrayOffset + 3] = sprite.angle;
  53511. this._vertexData[arrayOffset + 4] = sprite.width;
  53512. this._vertexData[arrayOffset + 5] = sprite.height;
  53513. this._vertexData[arrayOffset + 6] = offsetX;
  53514. this._vertexData[arrayOffset + 7] = offsetY;
  53515. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53516. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53517. var offset = (sprite.cellIndex / rowSize) >> 0;
  53518. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53519. this._vertexData[arrayOffset + 11] = offset;
  53520. // Color
  53521. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53522. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53523. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53524. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53525. };
  53526. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53527. var count = Math.min(this._capacity, this.sprites.length);
  53528. var min = BABYLON.Vector3.Zero();
  53529. var max = BABYLON.Vector3.Zero();
  53530. var distance = Number.MAX_VALUE;
  53531. var currentSprite = null;
  53532. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53533. var cameraView = camera.getViewMatrix();
  53534. for (var index = 0; index < count; index++) {
  53535. var sprite = this.sprites[index];
  53536. if (!sprite) {
  53537. continue;
  53538. }
  53539. if (predicate) {
  53540. if (!predicate(sprite)) {
  53541. continue;
  53542. }
  53543. }
  53544. else if (!sprite.isPickable) {
  53545. continue;
  53546. }
  53547. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53548. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53549. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53550. if (ray.intersectsBoxMinMax(min, max)) {
  53551. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53552. if (distance > currentDistance) {
  53553. distance = currentDistance;
  53554. currentSprite = sprite;
  53555. if (fastCheck) {
  53556. break;
  53557. }
  53558. }
  53559. }
  53560. }
  53561. if (currentSprite) {
  53562. var result = new BABYLON.PickingInfo();
  53563. result.hit = true;
  53564. result.pickedSprite = currentSprite;
  53565. result.distance = distance;
  53566. return result;
  53567. }
  53568. return null;
  53569. };
  53570. SpriteManager.prototype.render = function () {
  53571. // Check
  53572. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53573. return;
  53574. var engine = this._scene.getEngine();
  53575. var baseSize = this._spriteTexture.getBaseSize();
  53576. // Sprites
  53577. var deltaTime = engine.getDeltaTime();
  53578. var max = Math.min(this._capacity, this.sprites.length);
  53579. var rowSize = baseSize.width / this.cellWidth;
  53580. var offset = 0;
  53581. for (var index = 0; index < max; index++) {
  53582. var sprite = this.sprites[index];
  53583. if (!sprite || !sprite.isVisible) {
  53584. continue;
  53585. }
  53586. sprite._animate(deltaTime);
  53587. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53588. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53589. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53590. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53591. }
  53592. this._buffer.update(this._vertexData);
  53593. // Render
  53594. var effect = this._effectBase;
  53595. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53596. effect = this._effectFog;
  53597. }
  53598. engine.enableEffect(effect);
  53599. var viewMatrix = this._scene.getViewMatrix();
  53600. effect.setTexture("diffuseSampler", this._spriteTexture);
  53601. effect.setMatrix("view", viewMatrix);
  53602. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53603. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53604. // Fog
  53605. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53606. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53607. effect.setColor3("vFogColor", this._scene.fogColor);
  53608. }
  53609. // VBOs
  53610. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53611. // Draw order
  53612. engine.setDepthFunctionToLessOrEqual();
  53613. effect.setBool("alphaTest", true);
  53614. engine.setColorWrite(false);
  53615. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53616. engine.setColorWrite(true);
  53617. effect.setBool("alphaTest", false);
  53618. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53619. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53620. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53621. };
  53622. SpriteManager.prototype.dispose = function () {
  53623. if (this._buffer) {
  53624. this._buffer.dispose();
  53625. this._buffer = null;
  53626. }
  53627. if (this._indexBuffer) {
  53628. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53629. this._indexBuffer = null;
  53630. }
  53631. if (this._spriteTexture) {
  53632. this._spriteTexture.dispose();
  53633. this._spriteTexture = null;
  53634. }
  53635. // Remove from scene
  53636. var index = this._scene.spriteManagers.indexOf(this);
  53637. this._scene.spriteManagers.splice(index, 1);
  53638. // Callback
  53639. this.onDisposeObservable.notifyObservers(this);
  53640. this.onDisposeObservable.clear();
  53641. };
  53642. return SpriteManager;
  53643. }());
  53644. BABYLON.SpriteManager = SpriteManager;
  53645. })(BABYLON || (BABYLON = {}));
  53646. //# sourceMappingURL=babylon.spriteManager.js.map
  53647. var BABYLON;
  53648. (function (BABYLON) {
  53649. var Sprite = /** @class */ (function () {
  53650. function Sprite(name, manager) {
  53651. this.name = name;
  53652. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53653. this.width = 1.0;
  53654. this.height = 1.0;
  53655. this.angle = 0;
  53656. this.cellIndex = 0;
  53657. this.invertU = 0;
  53658. this.invertV = 0;
  53659. this.animations = new Array();
  53660. this.isPickable = false;
  53661. this._animationStarted = false;
  53662. this._loopAnimation = false;
  53663. this._fromIndex = 0;
  53664. this._toIndex = 0;
  53665. this._delay = 0;
  53666. this._direction = 1;
  53667. this._time = 0;
  53668. /**
  53669. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53670. */
  53671. this.isVisible = true;
  53672. this._manager = manager;
  53673. this._manager.sprites.push(this);
  53674. this.position = BABYLON.Vector3.Zero();
  53675. }
  53676. Object.defineProperty(Sprite.prototype, "size", {
  53677. get: function () {
  53678. return this.width;
  53679. },
  53680. set: function (value) {
  53681. this.width = value;
  53682. this.height = value;
  53683. },
  53684. enumerable: true,
  53685. configurable: true
  53686. });
  53687. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53688. this._fromIndex = from;
  53689. this._toIndex = to;
  53690. this._loopAnimation = loop;
  53691. this._delay = delay;
  53692. this._animationStarted = true;
  53693. this._direction = from < to ? 1 : -1;
  53694. this.cellIndex = from;
  53695. this._time = 0;
  53696. this._onAnimationEnd = onAnimationEnd;
  53697. };
  53698. Sprite.prototype.stopAnimation = function () {
  53699. this._animationStarted = false;
  53700. };
  53701. Sprite.prototype._animate = function (deltaTime) {
  53702. if (!this._animationStarted)
  53703. return;
  53704. this._time += deltaTime;
  53705. if (this._time > this._delay) {
  53706. this._time = this._time % this._delay;
  53707. this.cellIndex += this._direction;
  53708. if (this.cellIndex > this._toIndex) {
  53709. if (this._loopAnimation) {
  53710. this.cellIndex = this._fromIndex;
  53711. }
  53712. else {
  53713. this.cellIndex = this._toIndex;
  53714. this._animationStarted = false;
  53715. if (this._onAnimationEnd) {
  53716. this._onAnimationEnd();
  53717. }
  53718. if (this.disposeWhenFinishedAnimating) {
  53719. this.dispose();
  53720. }
  53721. }
  53722. }
  53723. }
  53724. };
  53725. Sprite.prototype.dispose = function () {
  53726. for (var i = 0; i < this._manager.sprites.length; i++) {
  53727. if (this._manager.sprites[i] == this) {
  53728. this._manager.sprites.splice(i, 1);
  53729. }
  53730. }
  53731. };
  53732. return Sprite;
  53733. }());
  53734. BABYLON.Sprite = Sprite;
  53735. })(BABYLON || (BABYLON = {}));
  53736. //# sourceMappingURL=babylon.sprite.js.map
  53737. var BABYLON;
  53738. (function (BABYLON) {
  53739. var IntersectionInfo = /** @class */ (function () {
  53740. function IntersectionInfo(bu, bv, distance) {
  53741. this.bu = bu;
  53742. this.bv = bv;
  53743. this.distance = distance;
  53744. this.faceId = 0;
  53745. this.subMeshId = 0;
  53746. }
  53747. return IntersectionInfo;
  53748. }());
  53749. BABYLON.IntersectionInfo = IntersectionInfo;
  53750. /**
  53751. * Information about the result of picking within a scene
  53752. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53753. */
  53754. var PickingInfo = /** @class */ (function () {
  53755. function PickingInfo() {
  53756. /**
  53757. * If the pick collided with an object
  53758. */
  53759. this.hit = false;
  53760. /**
  53761. * Distance away where the pick collided
  53762. */
  53763. this.distance = 0;
  53764. /**
  53765. * The location of pick collision
  53766. */
  53767. this.pickedPoint = null;
  53768. /**
  53769. * The mesh corrisponding the the pick collision
  53770. */
  53771. this.pickedMesh = null;
  53772. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53773. this.bu = 0;
  53774. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53775. this.bv = 0;
  53776. /** The id of the face on the mesh that was picked */
  53777. this.faceId = -1;
  53778. /** Id of the the submesh that was picked */
  53779. this.subMeshId = 0;
  53780. /** If a sprite was picked, this will be the sprite the pick collided with */
  53781. this.pickedSprite = null;
  53782. /**
  53783. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53784. */
  53785. this.originMesh = null;
  53786. /**
  53787. * The ray that was used to perform the picking.
  53788. */
  53789. this.ray = null;
  53790. }
  53791. /**
  53792. * Gets the normal corrispodning to the face the pick collided with
  53793. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53794. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53795. * @returns The normal corrispodning to the face the pick collided with
  53796. */
  53797. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53798. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53799. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53800. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53801. return null;
  53802. }
  53803. var indices = this.pickedMesh.getIndices();
  53804. if (!indices) {
  53805. return null;
  53806. }
  53807. var result;
  53808. if (useVerticesNormals) {
  53809. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53810. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53811. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53812. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53813. normal0 = normal0.scale(this.bu);
  53814. normal1 = normal1.scale(this.bv);
  53815. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53816. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53817. }
  53818. else {
  53819. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53820. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53821. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53822. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53823. var p1p2 = vertex1.subtract(vertex2);
  53824. var p3p2 = vertex3.subtract(vertex2);
  53825. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53826. }
  53827. if (useWorldCoordinates) {
  53828. var wm = this.pickedMesh.getWorldMatrix();
  53829. if (this.pickedMesh.nonUniformScaling) {
  53830. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53831. wm = BABYLON.Tmp.Matrix[0];
  53832. wm.setTranslationFromFloats(0, 0, 0);
  53833. wm.invert();
  53834. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53835. wm = BABYLON.Tmp.Matrix[1];
  53836. }
  53837. result = BABYLON.Vector3.TransformNormal(result, wm);
  53838. }
  53839. result.normalize();
  53840. return result;
  53841. };
  53842. /**
  53843. * Gets the texture coordinates of where the pick occured
  53844. * @returns the vector containing the coordnates of the texture
  53845. */
  53846. PickingInfo.prototype.getTextureCoordinates = function () {
  53847. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53848. return null;
  53849. }
  53850. var indices = this.pickedMesh.getIndices();
  53851. if (!indices) {
  53852. return null;
  53853. }
  53854. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53855. if (!uvs) {
  53856. return null;
  53857. }
  53858. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53859. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53860. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53861. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53862. uv1 = uv1.scale(this.bu);
  53863. uv2 = uv2.scale(this.bv);
  53864. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53865. };
  53866. return PickingInfo;
  53867. }());
  53868. BABYLON.PickingInfo = PickingInfo;
  53869. })(BABYLON || (BABYLON = {}));
  53870. //# sourceMappingURL=babylon.pickingInfo.js.map
  53871. var BABYLON;
  53872. (function (BABYLON) {
  53873. var Ray = /** @class */ (function () {
  53874. function Ray(origin, direction, length) {
  53875. if (length === void 0) { length = Number.MAX_VALUE; }
  53876. this.origin = origin;
  53877. this.direction = direction;
  53878. this.length = length;
  53879. }
  53880. // Methods
  53881. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53882. var d = 0.0;
  53883. var maxValue = Number.MAX_VALUE;
  53884. var inv;
  53885. var min;
  53886. var max;
  53887. var temp;
  53888. if (Math.abs(this.direction.x) < 0.0000001) {
  53889. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53890. return false;
  53891. }
  53892. }
  53893. else {
  53894. inv = 1.0 / this.direction.x;
  53895. min = (minimum.x - this.origin.x) * inv;
  53896. max = (maximum.x - this.origin.x) * inv;
  53897. if (max === -Infinity) {
  53898. max = Infinity;
  53899. }
  53900. if (min > max) {
  53901. temp = min;
  53902. min = max;
  53903. max = temp;
  53904. }
  53905. d = Math.max(min, d);
  53906. maxValue = Math.min(max, maxValue);
  53907. if (d > maxValue) {
  53908. return false;
  53909. }
  53910. }
  53911. if (Math.abs(this.direction.y) < 0.0000001) {
  53912. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53913. return false;
  53914. }
  53915. }
  53916. else {
  53917. inv = 1.0 / this.direction.y;
  53918. min = (minimum.y - this.origin.y) * inv;
  53919. max = (maximum.y - this.origin.y) * inv;
  53920. if (max === -Infinity) {
  53921. max = Infinity;
  53922. }
  53923. if (min > max) {
  53924. temp = min;
  53925. min = max;
  53926. max = temp;
  53927. }
  53928. d = Math.max(min, d);
  53929. maxValue = Math.min(max, maxValue);
  53930. if (d > maxValue) {
  53931. return false;
  53932. }
  53933. }
  53934. if (Math.abs(this.direction.z) < 0.0000001) {
  53935. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53936. return false;
  53937. }
  53938. }
  53939. else {
  53940. inv = 1.0 / this.direction.z;
  53941. min = (minimum.z - this.origin.z) * inv;
  53942. max = (maximum.z - this.origin.z) * inv;
  53943. if (max === -Infinity) {
  53944. max = Infinity;
  53945. }
  53946. if (min > max) {
  53947. temp = min;
  53948. min = max;
  53949. max = temp;
  53950. }
  53951. d = Math.max(min, d);
  53952. maxValue = Math.min(max, maxValue);
  53953. if (d > maxValue) {
  53954. return false;
  53955. }
  53956. }
  53957. return true;
  53958. };
  53959. Ray.prototype.intersectsBox = function (box) {
  53960. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53961. };
  53962. Ray.prototype.intersectsSphere = function (sphere) {
  53963. var x = sphere.center.x - this.origin.x;
  53964. var y = sphere.center.y - this.origin.y;
  53965. var z = sphere.center.z - this.origin.z;
  53966. var pyth = (x * x) + (y * y) + (z * z);
  53967. var rr = sphere.radius * sphere.radius;
  53968. if (pyth <= rr) {
  53969. return true;
  53970. }
  53971. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53972. if (dot < 0.0) {
  53973. return false;
  53974. }
  53975. var temp = pyth - (dot * dot);
  53976. return temp <= rr;
  53977. };
  53978. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53979. if (!this._edge1) {
  53980. this._edge1 = BABYLON.Vector3.Zero();
  53981. this._edge2 = BABYLON.Vector3.Zero();
  53982. this._pvec = BABYLON.Vector3.Zero();
  53983. this._tvec = BABYLON.Vector3.Zero();
  53984. this._qvec = BABYLON.Vector3.Zero();
  53985. }
  53986. vertex1.subtractToRef(vertex0, this._edge1);
  53987. vertex2.subtractToRef(vertex0, this._edge2);
  53988. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53989. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53990. if (det === 0) {
  53991. return null;
  53992. }
  53993. var invdet = 1 / det;
  53994. this.origin.subtractToRef(vertex0, this._tvec);
  53995. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53996. if (bu < 0 || bu > 1.0) {
  53997. return null;
  53998. }
  53999. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54000. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54001. if (bv < 0 || bu + bv > 1.0) {
  54002. return null;
  54003. }
  54004. //check if the distance is longer than the predefined length.
  54005. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54006. if (distance > this.length) {
  54007. return null;
  54008. }
  54009. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54010. };
  54011. Ray.prototype.intersectsPlane = function (plane) {
  54012. var distance;
  54013. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54014. if (Math.abs(result1) < 9.99999997475243E-07) {
  54015. return null;
  54016. }
  54017. else {
  54018. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54019. distance = (-plane.d - result2) / result1;
  54020. if (distance < 0.0) {
  54021. if (distance < -9.99999997475243E-07) {
  54022. return null;
  54023. }
  54024. else {
  54025. return 0;
  54026. }
  54027. }
  54028. return distance;
  54029. }
  54030. };
  54031. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54032. var tm = BABYLON.Tmp.Matrix[0];
  54033. mesh.getWorldMatrix().invertToRef(tm);
  54034. if (this._tmpRay) {
  54035. Ray.TransformToRef(this, tm, this._tmpRay);
  54036. }
  54037. else {
  54038. this._tmpRay = Ray.Transform(this, tm);
  54039. }
  54040. return mesh.intersects(this._tmpRay, fastCheck);
  54041. };
  54042. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54043. if (results) {
  54044. results.length = 0;
  54045. }
  54046. else {
  54047. results = [];
  54048. }
  54049. for (var i = 0; i < meshes.length; i++) {
  54050. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54051. if (pickInfo.hit) {
  54052. results.push(pickInfo);
  54053. }
  54054. }
  54055. results.sort(this._comparePickingInfo);
  54056. return results;
  54057. };
  54058. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54059. if (pickingInfoA.distance < pickingInfoB.distance) {
  54060. return -1;
  54061. }
  54062. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54063. return 1;
  54064. }
  54065. else {
  54066. return 0;
  54067. }
  54068. };
  54069. /**
  54070. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54071. * @param sega the first point of the segment to test the intersection against
  54072. * @param segb the second point of the segment to test the intersection against
  54073. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54074. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54075. */
  54076. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54077. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54078. var u = segb.subtract(sega);
  54079. var v = rsegb.subtract(this.origin);
  54080. var w = sega.subtract(this.origin);
  54081. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54082. var b = BABYLON.Vector3.Dot(u, v);
  54083. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54084. var d = BABYLON.Vector3.Dot(u, w);
  54085. var e = BABYLON.Vector3.Dot(v, w);
  54086. var D = a * c - b * b; // always >= 0
  54087. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54088. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54089. // compute the line parameters of the two closest points
  54090. if (D < Ray.smallnum) { // the lines are almost parallel
  54091. sN = 0.0; // force using point P0 on segment S1
  54092. sD = 1.0; // to prevent possible division by 0.0 later
  54093. tN = e;
  54094. tD = c;
  54095. }
  54096. else { // get the closest points on the infinite lines
  54097. sN = (b * e - c * d);
  54098. tN = (a * e - b * d);
  54099. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54100. sN = 0.0;
  54101. tN = e;
  54102. tD = c;
  54103. }
  54104. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54105. sN = sD;
  54106. tN = e + b;
  54107. tD = c;
  54108. }
  54109. }
  54110. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54111. tN = 0.0;
  54112. // recompute sc for this edge
  54113. if (-d < 0.0) {
  54114. sN = 0.0;
  54115. }
  54116. else if (-d > a)
  54117. sN = sD;
  54118. else {
  54119. sN = -d;
  54120. sD = a;
  54121. }
  54122. }
  54123. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54124. tN = tD;
  54125. // recompute sc for this edge
  54126. if ((-d + b) < 0.0) {
  54127. sN = 0;
  54128. }
  54129. else if ((-d + b) > a) {
  54130. sN = sD;
  54131. }
  54132. else {
  54133. sN = (-d + b);
  54134. sD = a;
  54135. }
  54136. }
  54137. // finally do the division to get sc and tc
  54138. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54139. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54140. // get the difference of the two closest points
  54141. var qtc = v.multiplyByFloats(tc, tc, tc);
  54142. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54143. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54144. if (isIntersected) {
  54145. return qtc.length();
  54146. }
  54147. return -1;
  54148. };
  54149. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54150. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54151. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54152. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54153. this.direction.normalize();
  54154. return this;
  54155. };
  54156. // Statics
  54157. Ray.Zero = function () {
  54158. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54159. };
  54160. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54161. var result = Ray.Zero();
  54162. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54163. };
  54164. /**
  54165. * 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
  54166. * transformed to the given world matrix.
  54167. * @param origin The origin point
  54168. * @param end The end point
  54169. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54170. */
  54171. Ray.CreateNewFromTo = function (origin, end, world) {
  54172. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54173. var direction = end.subtract(origin);
  54174. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54175. direction.normalize();
  54176. return Ray.Transform(new Ray(origin, direction, length), world);
  54177. };
  54178. Ray.Transform = function (ray, matrix) {
  54179. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54180. Ray.TransformToRef(ray, matrix, result);
  54181. return result;
  54182. };
  54183. Ray.TransformToRef = function (ray, matrix, result) {
  54184. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54185. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54186. result.length = ray.length;
  54187. var dir = result.direction;
  54188. var len = dir.length();
  54189. if (!(len === 0 || len === 1)) {
  54190. var num = 1.0 / len;
  54191. dir.x *= num;
  54192. dir.y *= num;
  54193. dir.z *= num;
  54194. result.length *= len;
  54195. }
  54196. };
  54197. Ray.smallnum = 0.00000001;
  54198. Ray.rayl = 10e8;
  54199. return Ray;
  54200. }());
  54201. BABYLON.Ray = Ray;
  54202. })(BABYLON || (BABYLON = {}));
  54203. //# sourceMappingURL=babylon.ray.js.map
  54204. var BABYLON;
  54205. (function (BABYLON) {
  54206. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54207. if (boxMin.x > sphereCenter.x + sphereRadius)
  54208. return false;
  54209. if (sphereCenter.x - sphereRadius > boxMax.x)
  54210. return false;
  54211. if (boxMin.y > sphereCenter.y + sphereRadius)
  54212. return false;
  54213. if (sphereCenter.y - sphereRadius > boxMax.y)
  54214. return false;
  54215. if (boxMin.z > sphereCenter.z + sphereRadius)
  54216. return false;
  54217. if (sphereCenter.z - sphereRadius > boxMax.z)
  54218. return false;
  54219. return true;
  54220. };
  54221. var getLowestRoot = (function () {
  54222. var result = { root: 0, found: false };
  54223. return function (a, b, c, maxR) {
  54224. result.root = 0;
  54225. result.found = false;
  54226. var determinant = b * b - 4.0 * a * c;
  54227. if (determinant < 0)
  54228. return result;
  54229. var sqrtD = Math.sqrt(determinant);
  54230. var r1 = (-b - sqrtD) / (2.0 * a);
  54231. var r2 = (-b + sqrtD) / (2.0 * a);
  54232. if (r1 > r2) {
  54233. var temp = r2;
  54234. r2 = r1;
  54235. r1 = temp;
  54236. }
  54237. if (r1 > 0 && r1 < maxR) {
  54238. result.root = r1;
  54239. result.found = true;
  54240. return result;
  54241. }
  54242. if (r2 > 0 && r2 < maxR) {
  54243. result.root = r2;
  54244. result.found = true;
  54245. return result;
  54246. }
  54247. return result;
  54248. };
  54249. })();
  54250. var Collider = /** @class */ (function () {
  54251. function Collider() {
  54252. this._collisionPoint = BABYLON.Vector3.Zero();
  54253. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54254. this._tempVector = BABYLON.Vector3.Zero();
  54255. this._tempVector2 = BABYLON.Vector3.Zero();
  54256. this._tempVector3 = BABYLON.Vector3.Zero();
  54257. this._tempVector4 = BABYLON.Vector3.Zero();
  54258. this._edge = BABYLON.Vector3.Zero();
  54259. this._baseToVertex = BABYLON.Vector3.Zero();
  54260. this._destinationPoint = BABYLON.Vector3.Zero();
  54261. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54262. this._displacementVector = BABYLON.Vector3.Zero();
  54263. this._radius = BABYLON.Vector3.One();
  54264. this._retry = 0;
  54265. this._basePointWorld = BABYLON.Vector3.Zero();
  54266. this._velocityWorld = BABYLON.Vector3.Zero();
  54267. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54268. this._collisionMask = -1;
  54269. }
  54270. Object.defineProperty(Collider.prototype, "collisionMask", {
  54271. get: function () {
  54272. return this._collisionMask;
  54273. },
  54274. set: function (mask) {
  54275. this._collisionMask = !isNaN(mask) ? mask : -1;
  54276. },
  54277. enumerable: true,
  54278. configurable: true
  54279. });
  54280. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54281. /**
  54282. * Gets the plane normal used to compute the sliding response (in local space)
  54283. */
  54284. get: function () {
  54285. return this._slidePlaneNormal;
  54286. },
  54287. enumerable: true,
  54288. configurable: true
  54289. });
  54290. // Methods
  54291. Collider.prototype._initialize = function (source, dir, e) {
  54292. this._velocity = dir;
  54293. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54294. this._basePoint = source;
  54295. source.multiplyToRef(this._radius, this._basePointWorld);
  54296. dir.multiplyToRef(this._radius, this._velocityWorld);
  54297. this._velocityWorldLength = this._velocityWorld.length();
  54298. this._epsilon = e;
  54299. this.collisionFound = false;
  54300. };
  54301. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54302. pa.subtractToRef(point, this._tempVector);
  54303. pb.subtractToRef(point, this._tempVector2);
  54304. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54305. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54306. if (d < 0)
  54307. return false;
  54308. pc.subtractToRef(point, this._tempVector3);
  54309. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54310. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54311. if (d < 0)
  54312. return false;
  54313. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54314. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54315. return d >= 0;
  54316. };
  54317. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54318. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54319. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54320. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54321. return false;
  54322. }
  54323. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54324. return false;
  54325. return true;
  54326. };
  54327. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54328. var t0;
  54329. var embeddedInPlane = false;
  54330. //defensive programming, actually not needed.
  54331. if (!trianglePlaneArray) {
  54332. trianglePlaneArray = [];
  54333. }
  54334. if (!trianglePlaneArray[faceIndex]) {
  54335. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54336. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54337. }
  54338. var trianglePlane = trianglePlaneArray[faceIndex];
  54339. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54340. return;
  54341. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54342. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54343. if (normalDotVelocity == 0) {
  54344. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54345. return;
  54346. embeddedInPlane = true;
  54347. t0 = 0;
  54348. }
  54349. else {
  54350. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54351. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54352. if (t0 > t1) {
  54353. var temp = t1;
  54354. t1 = t0;
  54355. t0 = temp;
  54356. }
  54357. if (t0 > 1.0 || t1 < 0.0)
  54358. return;
  54359. if (t0 < 0)
  54360. t0 = 0;
  54361. if (t0 > 1.0)
  54362. t0 = 1.0;
  54363. }
  54364. this._collisionPoint.copyFromFloats(0, 0, 0);
  54365. var found = false;
  54366. var t = 1.0;
  54367. if (!embeddedInPlane) {
  54368. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54369. this._velocity.scaleToRef(t0, this._tempVector);
  54370. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54371. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54372. found = true;
  54373. t = t0;
  54374. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54375. }
  54376. }
  54377. if (!found) {
  54378. var velocitySquaredLength = this._velocity.lengthSquared();
  54379. var a = velocitySquaredLength;
  54380. this._basePoint.subtractToRef(p1, this._tempVector);
  54381. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54382. var c = this._tempVector.lengthSquared() - 1.0;
  54383. var lowestRoot = getLowestRoot(a, b, c, t);
  54384. if (lowestRoot.found) {
  54385. t = lowestRoot.root;
  54386. found = true;
  54387. this._collisionPoint.copyFrom(p1);
  54388. }
  54389. this._basePoint.subtractToRef(p2, this._tempVector);
  54390. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54391. c = this._tempVector.lengthSquared() - 1.0;
  54392. lowestRoot = getLowestRoot(a, b, c, t);
  54393. if (lowestRoot.found) {
  54394. t = lowestRoot.root;
  54395. found = true;
  54396. this._collisionPoint.copyFrom(p2);
  54397. }
  54398. this._basePoint.subtractToRef(p3, this._tempVector);
  54399. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54400. c = this._tempVector.lengthSquared() - 1.0;
  54401. lowestRoot = getLowestRoot(a, b, c, t);
  54402. if (lowestRoot.found) {
  54403. t = lowestRoot.root;
  54404. found = true;
  54405. this._collisionPoint.copyFrom(p3);
  54406. }
  54407. p2.subtractToRef(p1, this._edge);
  54408. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54409. var edgeSquaredLength = this._edge.lengthSquared();
  54410. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54411. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54412. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54413. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54414. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54415. lowestRoot = getLowestRoot(a, b, c, t);
  54416. if (lowestRoot.found) {
  54417. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54418. if (f >= 0.0 && f <= 1.0) {
  54419. t = lowestRoot.root;
  54420. found = true;
  54421. this._edge.scaleInPlace(f);
  54422. p1.addToRef(this._edge, this._collisionPoint);
  54423. }
  54424. }
  54425. p3.subtractToRef(p2, this._edge);
  54426. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54427. edgeSquaredLength = this._edge.lengthSquared();
  54428. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54429. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54430. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54431. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54432. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54433. lowestRoot = getLowestRoot(a, b, c, t);
  54434. if (lowestRoot.found) {
  54435. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54436. if (f >= 0.0 && f <= 1.0) {
  54437. t = lowestRoot.root;
  54438. found = true;
  54439. this._edge.scaleInPlace(f);
  54440. p2.addToRef(this._edge, this._collisionPoint);
  54441. }
  54442. }
  54443. p1.subtractToRef(p3, this._edge);
  54444. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54445. edgeSquaredLength = this._edge.lengthSquared();
  54446. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54447. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54448. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54449. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54450. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54451. lowestRoot = getLowestRoot(a, b, c, t);
  54452. if (lowestRoot.found) {
  54453. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54454. if (f >= 0.0 && f <= 1.0) {
  54455. t = lowestRoot.root;
  54456. found = true;
  54457. this._edge.scaleInPlace(f);
  54458. p3.addToRef(this._edge, this._collisionPoint);
  54459. }
  54460. }
  54461. }
  54462. if (found) {
  54463. var distToCollision = t * this._velocity.length();
  54464. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54465. if (!this.intersectionPoint) {
  54466. this.intersectionPoint = this._collisionPoint.clone();
  54467. }
  54468. else {
  54469. this.intersectionPoint.copyFrom(this._collisionPoint);
  54470. }
  54471. this._nearestDistance = distToCollision;
  54472. this.collisionFound = true;
  54473. }
  54474. }
  54475. };
  54476. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54477. for (var i = indexStart; i < indexEnd; i += 3) {
  54478. var p1 = pts[indices[i] - decal];
  54479. var p2 = pts[indices[i + 1] - decal];
  54480. var p3 = pts[indices[i + 2] - decal];
  54481. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54482. }
  54483. };
  54484. Collider.prototype._getResponse = function (pos, vel) {
  54485. pos.addToRef(vel, this._destinationPoint);
  54486. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54487. this._basePoint.addToRef(vel, pos);
  54488. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54489. this._slidePlaneNormal.normalize();
  54490. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54491. pos.addInPlace(this._displacementVector);
  54492. this.intersectionPoint.addInPlace(this._displacementVector);
  54493. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54494. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54495. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54496. };
  54497. return Collider;
  54498. }());
  54499. BABYLON.Collider = Collider;
  54500. })(BABYLON || (BABYLON = {}));
  54501. //# sourceMappingURL=babylon.collider.js.map
  54502. var BABYLON;
  54503. (function (BABYLON) {
  54504. //WebWorker code will be inserted to this variable.
  54505. BABYLON.CollisionWorker = "";
  54506. /** Defines supported task for worker process */
  54507. var WorkerTaskType;
  54508. (function (WorkerTaskType) {
  54509. /** Initialization */
  54510. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54511. /** Update of geometry */
  54512. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54513. /** Evaluate collision */
  54514. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54515. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54516. /** Defines kind of replies returned by worker */
  54517. var WorkerReplyType;
  54518. (function (WorkerReplyType) {
  54519. /** Success */
  54520. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54521. /** Unkown error */
  54522. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54523. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54524. var CollisionCoordinatorWorker = /** @class */ (function () {
  54525. function CollisionCoordinatorWorker() {
  54526. var _this = this;
  54527. this._scaledPosition = BABYLON.Vector3.Zero();
  54528. this._scaledVelocity = BABYLON.Vector3.Zero();
  54529. this.onMeshUpdated = function (transformNode) {
  54530. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54531. };
  54532. this.onGeometryUpdated = function (geometry) {
  54533. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54534. };
  54535. this._afterRender = function () {
  54536. if (!_this._init)
  54537. return;
  54538. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54539. return;
  54540. }
  54541. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54542. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54543. if (_this._runningUpdated > 4) {
  54544. return;
  54545. }
  54546. ++_this._runningUpdated;
  54547. var payload = {
  54548. updatedMeshes: _this._addUpdateMeshesList,
  54549. updatedGeometries: _this._addUpdateGeometriesList,
  54550. removedGeometries: _this._toRemoveGeometryArray,
  54551. removedMeshes: _this._toRemoveMeshesArray
  54552. };
  54553. var message = {
  54554. payload: payload,
  54555. taskType: WorkerTaskType.UPDATE
  54556. };
  54557. var serializable = [];
  54558. for (var id in payload.updatedGeometries) {
  54559. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54560. //prepare transferables
  54561. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54562. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54563. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54564. }
  54565. }
  54566. _this._worker.postMessage(message, serializable);
  54567. _this._addUpdateMeshesList = {};
  54568. _this._addUpdateGeometriesList = {};
  54569. _this._toRemoveGeometryArray = [];
  54570. _this._toRemoveMeshesArray = [];
  54571. };
  54572. this._onMessageFromWorker = function (e) {
  54573. var returnData = e.data;
  54574. if (returnData.error != WorkerReplyType.SUCCESS) {
  54575. //TODO what errors can be returned from the worker?
  54576. BABYLON.Tools.Warn("error returned from worker!");
  54577. return;
  54578. }
  54579. switch (returnData.taskType) {
  54580. case WorkerTaskType.INIT:
  54581. _this._init = true;
  54582. //Update the worked with ALL of the scene's current state
  54583. _this._scene.meshes.forEach(function (mesh) {
  54584. _this.onMeshAdded(mesh);
  54585. });
  54586. _this._scene.getGeometries().forEach(function (geometry) {
  54587. _this.onGeometryAdded(geometry);
  54588. });
  54589. break;
  54590. case WorkerTaskType.UPDATE:
  54591. _this._runningUpdated--;
  54592. break;
  54593. case WorkerTaskType.COLLIDE:
  54594. var returnPayload = returnData.payload;
  54595. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54596. return;
  54597. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54598. if (callback) {
  54599. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54600. if (mesh) {
  54601. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54602. }
  54603. }
  54604. //cleanup
  54605. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54606. break;
  54607. }
  54608. };
  54609. this._collisionsCallbackArray = [];
  54610. this._init = false;
  54611. this._runningUpdated = 0;
  54612. this._addUpdateMeshesList = {};
  54613. this._addUpdateGeometriesList = {};
  54614. this._toRemoveGeometryArray = [];
  54615. this._toRemoveMeshesArray = [];
  54616. }
  54617. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54618. if (!this._init)
  54619. return;
  54620. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54621. return;
  54622. position.divideToRef(collider._radius, this._scaledPosition);
  54623. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54624. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54625. var payload = {
  54626. collider: {
  54627. position: this._scaledPosition.asArray(),
  54628. velocity: this._scaledVelocity.asArray(),
  54629. radius: collider._radius.asArray()
  54630. },
  54631. collisionId: collisionIndex,
  54632. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54633. maximumRetry: maximumRetry
  54634. };
  54635. var message = {
  54636. payload: payload,
  54637. taskType: WorkerTaskType.COLLIDE
  54638. };
  54639. this._worker.postMessage(message);
  54640. };
  54641. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54642. this._scene = scene;
  54643. this._scene.registerAfterRender(this._afterRender);
  54644. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54645. this._worker = new Worker(workerUrl);
  54646. this._worker.onmessage = this._onMessageFromWorker;
  54647. var message = {
  54648. payload: {},
  54649. taskType: WorkerTaskType.INIT
  54650. };
  54651. this._worker.postMessage(message);
  54652. };
  54653. CollisionCoordinatorWorker.prototype.destroy = function () {
  54654. this._scene.unregisterAfterRender(this._afterRender);
  54655. this._worker.terminate();
  54656. };
  54657. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54658. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54659. this.onMeshUpdated(mesh);
  54660. };
  54661. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54662. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54663. };
  54664. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54665. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54666. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54667. this.onGeometryUpdated(geometry);
  54668. };
  54669. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54670. this._toRemoveGeometryArray.push(geometry.id);
  54671. };
  54672. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54673. var submeshes = [];
  54674. if (mesh.subMeshes) {
  54675. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54676. var boundingInfo = sm.getBoundingInfo();
  54677. return {
  54678. position: idx,
  54679. verticesStart: sm.verticesStart,
  54680. verticesCount: sm.verticesCount,
  54681. indexStart: sm.indexStart,
  54682. indexCount: sm.indexCount,
  54683. hasMaterial: !!sm.getMaterial(),
  54684. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54685. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54686. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54687. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54688. };
  54689. });
  54690. }
  54691. var geometryId = null;
  54692. if (mesh instanceof BABYLON.Mesh) {
  54693. var geometry = mesh.geometry;
  54694. geometryId = geometry ? geometry.id : null;
  54695. }
  54696. else if (mesh instanceof BABYLON.InstancedMesh) {
  54697. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54698. geometryId = geometry ? geometry.id : null;
  54699. }
  54700. var boundingInfo = mesh.getBoundingInfo();
  54701. return {
  54702. uniqueId: mesh.uniqueId,
  54703. id: mesh.id,
  54704. name: mesh.name,
  54705. geometryId: geometryId,
  54706. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54707. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54708. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54709. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54710. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54711. subMeshes: submeshes,
  54712. checkCollisions: mesh.checkCollisions
  54713. };
  54714. };
  54715. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54716. return {
  54717. id: geometry.id,
  54718. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54719. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54720. indices: new Uint32Array(geometry.getIndices() || []),
  54721. };
  54722. };
  54723. return CollisionCoordinatorWorker;
  54724. }());
  54725. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54726. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54727. function CollisionCoordinatorLegacy() {
  54728. this._scaledPosition = BABYLON.Vector3.Zero();
  54729. this._scaledVelocity = BABYLON.Vector3.Zero();
  54730. this._finalPosition = BABYLON.Vector3.Zero();
  54731. }
  54732. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54733. position.divideToRef(collider._radius, this._scaledPosition);
  54734. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54735. collider.collidedMesh = null;
  54736. collider._retry = 0;
  54737. collider._initialVelocity = this._scaledVelocity;
  54738. collider._initialPosition = this._scaledPosition;
  54739. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54740. this._finalPosition.multiplyInPlace(collider._radius);
  54741. //run the callback
  54742. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54743. };
  54744. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54745. this._scene = scene;
  54746. };
  54747. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54748. //Legacy need no destruction method.
  54749. };
  54750. //No update in legacy mode
  54751. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54752. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54753. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54754. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54755. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54756. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54757. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54758. if (excludedMesh === void 0) { excludedMesh = null; }
  54759. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54760. if (collider._retry >= maximumRetry) {
  54761. finalPosition.copyFrom(position);
  54762. return;
  54763. }
  54764. // Check if this is a mesh else camera or -1
  54765. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54766. collider._initialize(position, velocity, closeDistance);
  54767. // Check all meshes
  54768. for (var index = 0; index < this._scene.meshes.length; index++) {
  54769. var mesh = this._scene.meshes[index];
  54770. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54771. mesh._checkCollision(collider);
  54772. }
  54773. }
  54774. if (!collider.collisionFound) {
  54775. position.addToRef(velocity, finalPosition);
  54776. return;
  54777. }
  54778. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54779. collider._getResponse(position, velocity);
  54780. }
  54781. if (velocity.length() <= closeDistance) {
  54782. finalPosition.copyFrom(position);
  54783. return;
  54784. }
  54785. collider._retry++;
  54786. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54787. };
  54788. return CollisionCoordinatorLegacy;
  54789. }());
  54790. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54791. })(BABYLON || (BABYLON = {}));
  54792. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54793. var BABYLON;
  54794. (function (BABYLON) {
  54795. /**
  54796. * A particle represents one of the element emitted by a particle system.
  54797. * This is mainly define by its coordinates, direction, velocity and age.
  54798. */
  54799. var Particle = /** @class */ (function () {
  54800. /**
  54801. * Creates a new instance Particle
  54802. * @param particleSystem the particle system the particle belongs to
  54803. */
  54804. function Particle(
  54805. /**
  54806. * particleSystem the particle system the particle belongs to.
  54807. */
  54808. particleSystem) {
  54809. this.particleSystem = particleSystem;
  54810. /**
  54811. * The world position of the particle in the scene.
  54812. */
  54813. this.position = BABYLON.Vector3.Zero();
  54814. /**
  54815. * The world direction of the particle in the scene.
  54816. */
  54817. this.direction = BABYLON.Vector3.Zero();
  54818. /**
  54819. * The color of the particle.
  54820. */
  54821. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54822. /**
  54823. * The color change of the particle per step.
  54824. */
  54825. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54826. /**
  54827. * Defines how long will the life of the particle be.
  54828. */
  54829. this.lifeTime = 1.0;
  54830. /**
  54831. * The current age of the particle.
  54832. */
  54833. this.age = 0;
  54834. /**
  54835. * The current size of the particle.
  54836. */
  54837. this.size = 0;
  54838. /**
  54839. * The current scale of the particle.
  54840. */
  54841. this.scale = new BABYLON.Vector2(1, 1);
  54842. /**
  54843. * The current angle of the particle.
  54844. */
  54845. this.angle = 0;
  54846. /**
  54847. * Defines how fast is the angle changing.
  54848. */
  54849. this.angularSpeed = 0;
  54850. /**
  54851. * Defines the cell index used by the particle to be rendered from a sprite.
  54852. */
  54853. this.cellIndex = 0;
  54854. /** @hidden */
  54855. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54856. /** @hidden */
  54857. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54858. /** @hidden */
  54859. this._currentSize1 = 0;
  54860. /** @hidden */
  54861. this._currentSize2 = 0;
  54862. /** @hidden */
  54863. this._currentAngularSpeed1 = 0;
  54864. /** @hidden */
  54865. this._currentAngularSpeed2 = 0;
  54866. /** @hidden */
  54867. this._currentVelocity1 = 0;
  54868. /** @hidden */
  54869. this._currentVelocity2 = 0;
  54870. if (!this.particleSystem.isAnimationSheetEnabled) {
  54871. return;
  54872. }
  54873. this.updateCellInfoFromSystem();
  54874. }
  54875. Particle.prototype.updateCellInfoFromSystem = function () {
  54876. this.cellIndex = this.particleSystem.startSpriteCellID;
  54877. };
  54878. /**
  54879. * Defines how the sprite cell index is updated for the particle
  54880. */
  54881. Particle.prototype.updateCellIndex = function () {
  54882. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54883. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54884. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54885. };
  54886. /**
  54887. * Copy the properties of particle to another one.
  54888. * @param other the particle to copy the information to.
  54889. */
  54890. Particle.prototype.copyTo = function (other) {
  54891. other.position.copyFrom(this.position);
  54892. if (this._initialDirection) {
  54893. if (other._initialDirection) {
  54894. other._initialDirection.copyFrom(this._initialDirection);
  54895. }
  54896. else {
  54897. other._initialDirection = this._initialDirection.clone();
  54898. }
  54899. }
  54900. else {
  54901. other._initialDirection = null;
  54902. }
  54903. other.direction.copyFrom(this.direction);
  54904. other.color.copyFrom(this.color);
  54905. other.colorStep.copyFrom(this.colorStep);
  54906. other.lifeTime = this.lifeTime;
  54907. other.age = this.age;
  54908. other.size = this.size;
  54909. other.scale.copyFrom(this.scale);
  54910. other.angle = this.angle;
  54911. other.angularSpeed = this.angularSpeed;
  54912. other.particleSystem = this.particleSystem;
  54913. other.cellIndex = this.cellIndex;
  54914. if (this._currentColorGradient) {
  54915. other._currentColorGradient = this._currentColorGradient;
  54916. other._currentColor1.copyFrom(this._currentColor1);
  54917. other._currentColor2.copyFrom(this._currentColor2);
  54918. }
  54919. if (this._currentSizeGradient) {
  54920. other._currentSizeGradient = this._currentSizeGradient;
  54921. other._currentSize1 = this._currentSize1;
  54922. other._currentSize2 = this._currentSize2;
  54923. }
  54924. if (this._currentAngularSpeedGradient) {
  54925. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54926. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54927. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54928. }
  54929. if (this._currentVelocityGradient) {
  54930. other._currentVelocityGradient = this._currentVelocityGradient;
  54931. other._currentVelocity1 = this._currentVelocity1;
  54932. other._currentVelocity2 = this._currentVelocity2;
  54933. }
  54934. if (this.particleSystem.isAnimationSheetEnabled) {
  54935. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54936. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54937. }
  54938. };
  54939. return Particle;
  54940. }());
  54941. BABYLON.Particle = Particle;
  54942. })(BABYLON || (BABYLON = {}));
  54943. //# sourceMappingURL=babylon.particle.js.map
  54944. var BABYLON;
  54945. (function (BABYLON) {
  54946. /**
  54947. * This represents a particle system in Babylon.
  54948. * 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.
  54949. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54950. * @example https://doc.babylonjs.com/babylon101/particles
  54951. */
  54952. var ParticleSystem = /** @class */ (function () {
  54953. /**
  54954. * Instantiates a particle system.
  54955. * 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.
  54956. * @param name The name of the particle system
  54957. * @param capacity The max number of particles alive at the same time
  54958. * @param scene The scene the particle system belongs to
  54959. * @param customEffect a custom effect used to change the way particles are rendered by default
  54960. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54961. * @param epsilon Offset used to render the particles
  54962. */
  54963. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54964. if (customEffect === void 0) { customEffect = null; }
  54965. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54966. if (epsilon === void 0) { epsilon = 0.01; }
  54967. var _this = this;
  54968. /**
  54969. * List of animations used by the particle system.
  54970. */
  54971. this.animations = [];
  54972. /**
  54973. * The rendering group used by the Particle system to chose when to render.
  54974. */
  54975. this.renderingGroupId = 0;
  54976. /**
  54977. * The emitter represents the Mesh or position we are attaching the particle system to.
  54978. */
  54979. this.emitter = null;
  54980. /**
  54981. * The maximum number of particles to emit per frame
  54982. */
  54983. this.emitRate = 10;
  54984. /**
  54985. * If you want to launch only a few particles at once, that can be done, as well.
  54986. */
  54987. this.manualEmitCount = -1;
  54988. /**
  54989. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54990. */
  54991. this.updateSpeed = 0.01;
  54992. /**
  54993. * The amount of time the particle system is running (depends of the overall update speed).
  54994. */
  54995. this.targetStopDuration = 0;
  54996. /**
  54997. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54998. */
  54999. this.disposeOnStop = false;
  55000. /**
  55001. * Minimum power of emitting particles.
  55002. */
  55003. this.minEmitPower = 1;
  55004. /**
  55005. * Maximum power of emitting particles.
  55006. */
  55007. this.maxEmitPower = 1;
  55008. /**
  55009. * Minimum life time of emitting particles.
  55010. */
  55011. this.minLifeTime = 1;
  55012. /**
  55013. * Maximum life time of emitting particles.
  55014. */
  55015. this.maxLifeTime = 1;
  55016. /**
  55017. * Minimum Size of emitting particles.
  55018. */
  55019. this.minSize = 1;
  55020. /**
  55021. * Maximum Size of emitting particles.
  55022. */
  55023. this.maxSize = 1;
  55024. /**
  55025. * Minimum scale of emitting particles on X axis.
  55026. */
  55027. this.minScaleX = 1;
  55028. /**
  55029. * Maximum scale of emitting particles on X axis.
  55030. */
  55031. this.maxScaleX = 1;
  55032. /**
  55033. * Minimum scale of emitting particles on Y axis.
  55034. */
  55035. this.minScaleY = 1;
  55036. /**
  55037. * Maximum scale of emitting particles on Y axis.
  55038. */
  55039. this.maxScaleY = 1;
  55040. /**
  55041. * Gets or sets the minimal initial rotation in radians.
  55042. */
  55043. this.minInitialRotation = 0;
  55044. /**
  55045. * Gets or sets the maximal initial rotation in radians.
  55046. */
  55047. this.maxInitialRotation = 0;
  55048. /**
  55049. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55050. */
  55051. this.minAngularSpeed = 0;
  55052. /**
  55053. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55054. */
  55055. this.maxAngularSpeed = 0;
  55056. /**
  55057. * The layer mask we are rendering the particles through.
  55058. */
  55059. this.layerMask = 0x0FFFFFFF;
  55060. /**
  55061. * This can help using your own shader to render the particle system.
  55062. * The according effect will be created
  55063. */
  55064. this.customShader = null;
  55065. /**
  55066. * By default particle system starts as soon as they are created. This prevents the
  55067. * automatic start to happen and let you decide when to start emitting particles.
  55068. */
  55069. this.preventAutoStart = false;
  55070. /**
  55071. * Callback triggered when the particle animation is ending.
  55072. */
  55073. this.onAnimationEnd = null;
  55074. /**
  55075. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55076. */
  55077. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55078. /**
  55079. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55080. * to override the particles.
  55081. */
  55082. this.forceDepthWrite = false;
  55083. /**
  55084. * You can use gravity if you want to give an orientation to your particles.
  55085. */
  55086. this.gravity = BABYLON.Vector3.Zero();
  55087. this._colorGradients = null;
  55088. this._sizeGradients = null;
  55089. this._lifeTimeGradients = null;
  55090. this._angularSpeedGradients = null;
  55091. this._velocityGradients = null;
  55092. /**
  55093. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55094. */
  55095. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55096. /**
  55097. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55098. */
  55099. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55100. /**
  55101. * Color the particle will have at the end of its lifetime
  55102. */
  55103. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55104. /**
  55105. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55106. */
  55107. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55108. /**
  55109. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55110. */
  55111. this.spriteCellChangeSpeed = 1;
  55112. /**
  55113. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55114. */
  55115. this.startSpriteCellID = 0;
  55116. /**
  55117. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55118. */
  55119. this.endSpriteCellID = 0;
  55120. /**
  55121. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55122. */
  55123. this.spriteCellWidth = 0;
  55124. /**
  55125. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55126. */
  55127. this.spriteCellHeight = 0;
  55128. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55129. this.preWarmCycles = 0;
  55130. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55131. this.preWarmStepOffset = 1;
  55132. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55133. this.translationPivot = new BABYLON.Vector2(0, 0);
  55134. /**
  55135. * An event triggered when the system is disposed
  55136. */
  55137. this.onDisposeObservable = new BABYLON.Observable();
  55138. /**
  55139. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55140. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55141. */
  55142. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55143. this._particles = new Array();
  55144. this._stockParticles = new Array();
  55145. this._newPartsExcess = 0;
  55146. this._vertexBuffers = {};
  55147. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55148. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55149. this._scaledDirection = BABYLON.Vector3.Zero();
  55150. this._scaledGravity = BABYLON.Vector3.Zero();
  55151. this._currentRenderId = -1;
  55152. this._useInstancing = false;
  55153. this._started = false;
  55154. this._stopped = false;
  55155. this._actualFrame = 0;
  55156. this._isBillboardBased = true;
  55157. // start of sub system methods
  55158. /**
  55159. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55160. * Its lifetime will start back at 0.
  55161. */
  55162. this.recycleParticle = function (particle) {
  55163. var lastParticle = _this._particles.pop();
  55164. if (lastParticle !== particle) {
  55165. lastParticle.copyTo(particle);
  55166. }
  55167. _this._stockParticles.push(lastParticle);
  55168. };
  55169. this._createParticle = function () {
  55170. var particle;
  55171. if (_this._stockParticles.length !== 0) {
  55172. particle = _this._stockParticles.pop();
  55173. particle.age = 0;
  55174. particle._currentColorGradient = null;
  55175. particle.cellIndex = _this.startSpriteCellID;
  55176. }
  55177. else {
  55178. particle = new BABYLON.Particle(_this);
  55179. }
  55180. return particle;
  55181. };
  55182. this._emitFromParticle = function (particle) {
  55183. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55184. return;
  55185. }
  55186. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55187. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55188. subSystem._rootParticleSystem = _this;
  55189. _this.activeSubSystems.push(subSystem);
  55190. subSystem.start();
  55191. };
  55192. this.id = name;
  55193. this.name = name;
  55194. this._capacity = capacity;
  55195. this._epsilon = epsilon;
  55196. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55197. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55198. this._customEffect = customEffect;
  55199. scene.particleSystems.push(this);
  55200. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55201. this._createIndexBuffer();
  55202. this._createVertexBuffers();
  55203. // Default emitter type
  55204. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55205. this.updateFunction = function (particles) {
  55206. var _loop_1 = function () {
  55207. particle = particles[index];
  55208. particle.age += _this._scaledUpdateSpeed;
  55209. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55210. _this._emitFromParticle(particle);
  55211. _this.recycleParticle(particle);
  55212. index--;
  55213. return "continue";
  55214. }
  55215. else {
  55216. var ratio = particle.age / particle.lifeTime;
  55217. // Color
  55218. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55219. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55220. if (currentGradient !== particle._currentColorGradient) {
  55221. particle._currentColor1.copyFrom(particle._currentColor2);
  55222. nextGradient.getColorToRef(particle._currentColor2);
  55223. particle._currentColorGradient = currentGradient;
  55224. }
  55225. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55226. });
  55227. }
  55228. else {
  55229. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55230. particle.color.addInPlace(_this._scaledColorStep);
  55231. if (particle.color.a < 0) {
  55232. particle.color.a = 0;
  55233. }
  55234. }
  55235. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55236. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55237. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55238. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55239. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55240. particle._currentAngularSpeedGradient = currentGradient;
  55241. }
  55242. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55243. });
  55244. }
  55245. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55246. var directionScale_1 = _this._scaledUpdateSpeed;
  55247. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  55248. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  55249. if (currentGradient !== particle._currentVelocityGradient) {
  55250. particle._currentVelocity1 = particle._currentVelocity2;
  55251. particle._currentVelocity2 = nextGradient.getFactor();
  55252. particle._currentVelocityGradient = currentGradient;
  55253. }
  55254. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  55255. });
  55256. }
  55257. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  55258. particle.position.addInPlace(_this._scaledDirection);
  55259. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55260. particle.direction.addInPlace(_this._scaledGravity);
  55261. // Size
  55262. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55263. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55264. if (currentGradient !== particle._currentSizeGradient) {
  55265. particle._currentSize1 = particle._currentSize2;
  55266. particle._currentSize2 = nextGradient.getFactor();
  55267. particle._currentSizeGradient = currentGradient;
  55268. }
  55269. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55270. });
  55271. }
  55272. if (_this._isAnimationSheetEnabled) {
  55273. particle.updateCellIndex();
  55274. }
  55275. }
  55276. };
  55277. var particle;
  55278. for (var index = 0; index < particles.length; index++) {
  55279. _loop_1();
  55280. }
  55281. };
  55282. }
  55283. /**
  55284. * Gets the current list of color gradients.
  55285. * You must use addColorGradient and removeColorGradient to udpate this list
  55286. * @returns the list of color gradients
  55287. */
  55288. ParticleSystem.prototype.getColorGradients = function () {
  55289. return this._colorGradients;
  55290. };
  55291. /**
  55292. * Gets the current list of size gradients.
  55293. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55294. * @returns the list of size gradients
  55295. */
  55296. ParticleSystem.prototype.getSizeGradients = function () {
  55297. return this._sizeGradients;
  55298. };
  55299. /**
  55300. * Gets the current list of life time gradients.
  55301. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55302. * @returns the list of life time gradients
  55303. */
  55304. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55305. return this._lifeTimeGradients;
  55306. };
  55307. /**
  55308. * Gets the current list of angular speed gradients.
  55309. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55310. * @returns the list of angular speed gradients
  55311. */
  55312. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55313. return this._angularSpeedGradients;
  55314. };
  55315. /**
  55316. * Gets the current list of velocity gradients.
  55317. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55318. * @returns the list of velocity gradients
  55319. */
  55320. ParticleSystem.prototype.getVelocityGradients = function () {
  55321. return this._velocityGradients;
  55322. };
  55323. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55324. /**
  55325. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55326. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55327. */
  55328. get: function () {
  55329. if (this.particleEmitterType.direction1) {
  55330. return this.particleEmitterType.direction1;
  55331. }
  55332. return BABYLON.Vector3.Zero();
  55333. },
  55334. set: function (value) {
  55335. if (this.particleEmitterType.direction1) {
  55336. this.particleEmitterType.direction1 = value;
  55337. }
  55338. },
  55339. enumerable: true,
  55340. configurable: true
  55341. });
  55342. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55343. /**
  55344. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55345. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55346. */
  55347. get: function () {
  55348. if (this.particleEmitterType.direction2) {
  55349. return this.particleEmitterType.direction2;
  55350. }
  55351. return BABYLON.Vector3.Zero();
  55352. },
  55353. set: function (value) {
  55354. if (this.particleEmitterType.direction2) {
  55355. this.particleEmitterType.direction2 = value;
  55356. }
  55357. },
  55358. enumerable: true,
  55359. configurable: true
  55360. });
  55361. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55362. /**
  55363. * 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.
  55364. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55365. */
  55366. get: function () {
  55367. if (this.particleEmitterType.minEmitBox) {
  55368. return this.particleEmitterType.minEmitBox;
  55369. }
  55370. return BABYLON.Vector3.Zero();
  55371. },
  55372. set: function (value) {
  55373. if (this.particleEmitterType.minEmitBox) {
  55374. this.particleEmitterType.minEmitBox = value;
  55375. }
  55376. },
  55377. enumerable: true,
  55378. configurable: true
  55379. });
  55380. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55381. /**
  55382. * 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.
  55383. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55384. */
  55385. get: function () {
  55386. if (this.particleEmitterType.maxEmitBox) {
  55387. return this.particleEmitterType.maxEmitBox;
  55388. }
  55389. return BABYLON.Vector3.Zero();
  55390. },
  55391. set: function (value) {
  55392. if (this.particleEmitterType.maxEmitBox) {
  55393. this.particleEmitterType.maxEmitBox = value;
  55394. }
  55395. },
  55396. enumerable: true,
  55397. configurable: true
  55398. });
  55399. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55400. /**
  55401. * Sets a callback that will be triggered when the system is disposed
  55402. */
  55403. set: function (callback) {
  55404. if (this._onDisposeObserver) {
  55405. this.onDisposeObservable.remove(this._onDisposeObserver);
  55406. }
  55407. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55408. },
  55409. enumerable: true,
  55410. configurable: true
  55411. });
  55412. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55413. /**
  55414. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55415. */
  55416. get: function () {
  55417. return this._isAnimationSheetEnabled;
  55418. },
  55419. enumerable: true,
  55420. configurable: true
  55421. });
  55422. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55423. /**
  55424. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55425. */
  55426. get: function () {
  55427. return this._isBillboardBased;
  55428. },
  55429. set: function (value) {
  55430. if (this._isBillboardBased === value) {
  55431. return;
  55432. }
  55433. this._isBillboardBased = value;
  55434. this._resetEffect();
  55435. },
  55436. enumerable: true,
  55437. configurable: true
  55438. });
  55439. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55440. //end of Sub-emitter
  55441. /**
  55442. * Gets the current list of active particles
  55443. */
  55444. get: function () {
  55445. return this._particles;
  55446. },
  55447. enumerable: true,
  55448. configurable: true
  55449. });
  55450. /**
  55451. * Returns the string "ParticleSystem"
  55452. * @returns a string containing the class name
  55453. */
  55454. ParticleSystem.prototype.getClassName = function () {
  55455. return "ParticleSystem";
  55456. };
  55457. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55458. var newGradient = new BABYLON.FactorGradient();
  55459. newGradient.gradient = gradient;
  55460. newGradient.factor1 = factor;
  55461. newGradient.factor2 = factor2;
  55462. factorGradients.push(newGradient);
  55463. factorGradients.sort(function (a, b) {
  55464. if (a.gradient < b.gradient) {
  55465. return -1;
  55466. }
  55467. else if (a.gradient > b.gradient) {
  55468. return 1;
  55469. }
  55470. return 0;
  55471. });
  55472. };
  55473. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55474. if (!factorGradients) {
  55475. return;
  55476. }
  55477. var index = 0;
  55478. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55479. var factorGradient = factorGradients_1[_i];
  55480. if (factorGradient.gradient === gradient) {
  55481. factorGradients.splice(index, 1);
  55482. break;
  55483. }
  55484. index++;
  55485. }
  55486. };
  55487. /**
  55488. * Adds a new life time gradient
  55489. * @param gradient defines the gradient to use (between 0 and 1)
  55490. * @param factor defines the life time factor to affect to the specified gradient
  55491. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55492. * @returns the current particle system
  55493. */
  55494. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55495. if (!this._lifeTimeGradients) {
  55496. this._lifeTimeGradients = [];
  55497. }
  55498. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55499. return this;
  55500. };
  55501. /**
  55502. * Remove a specific life time gradient
  55503. * @param gradient defines the gradient to remove
  55504. * @returns the current particle system
  55505. */
  55506. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55507. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55508. return this;
  55509. };
  55510. /**
  55511. * Adds a new size gradient
  55512. * @param gradient defines the gradient to use (between 0 and 1)
  55513. * @param factor defines the size factor to affect to the specified gradient
  55514. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55515. * @returns the current particle system
  55516. */
  55517. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55518. if (!this._sizeGradients) {
  55519. this._sizeGradients = [];
  55520. }
  55521. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55522. return this;
  55523. };
  55524. /**
  55525. * Remove a specific size gradient
  55526. * @param gradient defines the gradient to remove
  55527. * @returns the current particle system
  55528. */
  55529. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55530. this._removeFactorGradient(this._sizeGradients, gradient);
  55531. return this;
  55532. };
  55533. /**
  55534. * Adds a new angular speed gradient
  55535. * @param gradient defines the gradient to use (between 0 and 1)
  55536. * @param factor defines the size factor to affect to the specified gradient
  55537. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55538. * @returns the current particle system
  55539. */
  55540. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55541. if (!this._angularSpeedGradients) {
  55542. this._angularSpeedGradients = [];
  55543. }
  55544. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55545. return this;
  55546. };
  55547. /**
  55548. * Remove a specific angular speed gradient
  55549. * @param gradient defines the gradient to remove
  55550. * @returns the current particle system
  55551. */
  55552. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55553. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55554. return this;
  55555. };
  55556. /**
  55557. * Adds a new velocity gradient
  55558. * @param gradient defines the gradient to use (between 0 and 1)
  55559. * @param factor defines the size factor to affect to the specified gradient
  55560. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55561. * @returns the current particle system
  55562. */
  55563. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  55564. if (!this._velocityGradients) {
  55565. this._velocityGradients = [];
  55566. }
  55567. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  55568. return this;
  55569. };
  55570. /**
  55571. * Remove a specific velocity gradient
  55572. * @param gradient defines the gradient to remove
  55573. * @returns the current particle system
  55574. */
  55575. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  55576. this._removeFactorGradient(this._velocityGradients, gradient);
  55577. return this;
  55578. };
  55579. /**
  55580. * Adds a new color gradient
  55581. * @param gradient defines the gradient to use (between 0 and 1)
  55582. * @param color defines the color to affect to the specified gradient
  55583. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55584. */
  55585. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55586. if (!this._colorGradients) {
  55587. this._colorGradients = [];
  55588. }
  55589. var colorGradient = new BABYLON.ColorGradient();
  55590. colorGradient.gradient = gradient;
  55591. colorGradient.color1 = color;
  55592. colorGradient.color2 = color2;
  55593. this._colorGradients.push(colorGradient);
  55594. this._colorGradients.sort(function (a, b) {
  55595. if (a.gradient < b.gradient) {
  55596. return -1;
  55597. }
  55598. else if (a.gradient > b.gradient) {
  55599. return 1;
  55600. }
  55601. return 0;
  55602. });
  55603. return this;
  55604. };
  55605. /**
  55606. * Remove a specific color gradient
  55607. * @param gradient defines the gradient to remove
  55608. */
  55609. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55610. if (!this._colorGradients) {
  55611. return this;
  55612. }
  55613. var index = 0;
  55614. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55615. var colorGradient = _a[_i];
  55616. if (colorGradient.gradient === gradient) {
  55617. this._colorGradients.splice(index, 1);
  55618. break;
  55619. }
  55620. index++;
  55621. }
  55622. return this;
  55623. };
  55624. ParticleSystem.prototype._resetEffect = function () {
  55625. if (this._vertexBuffer) {
  55626. this._vertexBuffer.dispose();
  55627. this._vertexBuffer = null;
  55628. }
  55629. if (this._spriteBuffer) {
  55630. this._spriteBuffer.dispose();
  55631. this._spriteBuffer = null;
  55632. }
  55633. this._createVertexBuffers();
  55634. };
  55635. ParticleSystem.prototype._createVertexBuffers = function () {
  55636. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55637. if (this._isAnimationSheetEnabled) {
  55638. this._vertexBufferSize += 1;
  55639. }
  55640. if (!this._isBillboardBased) {
  55641. this._vertexBufferSize += 3;
  55642. }
  55643. var engine = this._scene.getEngine();
  55644. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55645. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55646. var dataOffset = 0;
  55647. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55648. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55649. dataOffset += 3;
  55650. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55651. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55652. dataOffset += 4;
  55653. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55654. this._vertexBuffers["angle"] = options;
  55655. dataOffset += 1;
  55656. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55657. this._vertexBuffers["size"] = size;
  55658. dataOffset += 2;
  55659. if (this._isAnimationSheetEnabled) {
  55660. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55661. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55662. dataOffset += 1;
  55663. }
  55664. if (!this._isBillboardBased) {
  55665. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55666. this._vertexBuffers["direction"] = directionBuffer;
  55667. dataOffset += 3;
  55668. }
  55669. var offsets;
  55670. if (this._useInstancing) {
  55671. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55672. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55673. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55674. }
  55675. else {
  55676. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55677. dataOffset += 2;
  55678. }
  55679. this._vertexBuffers["offset"] = offsets;
  55680. };
  55681. ParticleSystem.prototype._createIndexBuffer = function () {
  55682. if (this._useInstancing) {
  55683. return;
  55684. }
  55685. var indices = [];
  55686. var index = 0;
  55687. for (var count = 0; count < this._capacity; count++) {
  55688. indices.push(index);
  55689. indices.push(index + 1);
  55690. indices.push(index + 2);
  55691. indices.push(index);
  55692. indices.push(index + 2);
  55693. indices.push(index + 3);
  55694. index += 4;
  55695. }
  55696. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55697. };
  55698. /**
  55699. * Gets the maximum number of particles active at the same time.
  55700. * @returns The max number of active particles.
  55701. */
  55702. ParticleSystem.prototype.getCapacity = function () {
  55703. return this._capacity;
  55704. };
  55705. /**
  55706. * Gets Wether there are still active particles in the system.
  55707. * @returns True if it is alive, otherwise false.
  55708. */
  55709. ParticleSystem.prototype.isAlive = function () {
  55710. return this._alive;
  55711. };
  55712. /**
  55713. * Gets Wether the system has been started.
  55714. * @returns True if it has been started, otherwise false.
  55715. */
  55716. ParticleSystem.prototype.isStarted = function () {
  55717. return this._started;
  55718. };
  55719. /**
  55720. * Starts the particle system and begins to emit.
  55721. */
  55722. ParticleSystem.prototype.start = function () {
  55723. this._started = true;
  55724. this._stopped = false;
  55725. this._actualFrame = 0;
  55726. if (this.subEmitters && this.subEmitters.length != 0) {
  55727. this.activeSubSystems = new Array();
  55728. }
  55729. if (this.preWarmCycles) {
  55730. for (var index = 0; index < this.preWarmCycles; index++) {
  55731. this.animate(true);
  55732. }
  55733. }
  55734. };
  55735. /**
  55736. * Stops the particle system.
  55737. * @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.
  55738. */
  55739. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55740. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55741. this._stopped = true;
  55742. if (stopSubEmitters) {
  55743. this._stopSubEmitters();
  55744. }
  55745. };
  55746. // animation sheet
  55747. /**
  55748. * Remove all active particles
  55749. */
  55750. ParticleSystem.prototype.reset = function () {
  55751. this._stockParticles = [];
  55752. this._particles = [];
  55753. };
  55754. /**
  55755. * @hidden (for internal use only)
  55756. */
  55757. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55758. var offset = index * this._vertexBufferSize;
  55759. this._vertexData[offset++] = particle.position.x;
  55760. this._vertexData[offset++] = particle.position.y;
  55761. this._vertexData[offset++] = particle.position.z;
  55762. this._vertexData[offset++] = particle.color.r;
  55763. this._vertexData[offset++] = particle.color.g;
  55764. this._vertexData[offset++] = particle.color.b;
  55765. this._vertexData[offset++] = particle.color.a;
  55766. this._vertexData[offset++] = particle.angle;
  55767. this._vertexData[offset++] = particle.scale.x * particle.size;
  55768. this._vertexData[offset++] = particle.scale.y * particle.size;
  55769. if (this._isAnimationSheetEnabled) {
  55770. this._vertexData[offset++] = particle.cellIndex;
  55771. }
  55772. if (!this._isBillboardBased) {
  55773. if (particle._initialDirection) {
  55774. this._vertexData[offset++] = particle._initialDirection.x;
  55775. this._vertexData[offset++] = particle._initialDirection.y;
  55776. this._vertexData[offset++] = particle._initialDirection.z;
  55777. }
  55778. else {
  55779. this._vertexData[offset++] = particle.direction.x;
  55780. this._vertexData[offset++] = particle.direction.y;
  55781. this._vertexData[offset++] = particle.direction.z;
  55782. }
  55783. }
  55784. if (!this._useInstancing) {
  55785. if (this._isAnimationSheetEnabled) {
  55786. if (offsetX === 0)
  55787. offsetX = this._epsilon;
  55788. else if (offsetX === 1)
  55789. offsetX = 1 - this._epsilon;
  55790. if (offsetY === 0)
  55791. offsetY = this._epsilon;
  55792. else if (offsetY === 1)
  55793. offsetY = 1 - this._epsilon;
  55794. }
  55795. this._vertexData[offset++] = offsetX;
  55796. this._vertexData[offset++] = offsetY;
  55797. }
  55798. };
  55799. ParticleSystem.prototype._stopSubEmitters = function () {
  55800. if (!this.activeSubSystems) {
  55801. return;
  55802. }
  55803. this.activeSubSystems.forEach(function (subSystem) {
  55804. subSystem.stop(true);
  55805. });
  55806. this.activeSubSystems = new Array();
  55807. };
  55808. ParticleSystem.prototype._removeFromRoot = function () {
  55809. if (!this._rootParticleSystem) {
  55810. return;
  55811. }
  55812. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55813. if (index !== -1) {
  55814. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55815. }
  55816. };
  55817. // End of sub system methods
  55818. ParticleSystem.prototype._update = function (newParticles) {
  55819. // Update current
  55820. this._alive = this._particles.length > 0;
  55821. this.updateFunction(this._particles);
  55822. // Add new ones
  55823. var worldMatrix;
  55824. if (this.emitter.position) {
  55825. var emitterMesh = this.emitter;
  55826. worldMatrix = emitterMesh.getWorldMatrix();
  55827. }
  55828. else {
  55829. var emitterPosition = this.emitter;
  55830. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55831. }
  55832. var particle;
  55833. var _loop_2 = function () {
  55834. if (this_1._particles.length === this_1._capacity) {
  55835. return "break";
  55836. }
  55837. particle = this_1._createParticle();
  55838. this_1._particles.push(particle);
  55839. // Emitter
  55840. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55841. if (this_1.startPositionFunction) {
  55842. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55843. }
  55844. else {
  55845. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55846. }
  55847. if (this_1.startDirectionFunction) {
  55848. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55849. }
  55850. else {
  55851. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55852. }
  55853. if (emitPower === 0) {
  55854. if (!particle._initialDirection) {
  55855. particle._initialDirection = particle.direction.clone();
  55856. }
  55857. else {
  55858. particle._initialDirection.copyFrom(particle.direction);
  55859. }
  55860. }
  55861. else {
  55862. particle._initialDirection = null;
  55863. }
  55864. particle.direction.scaleInPlace(emitPower);
  55865. // Life time
  55866. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55867. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55868. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55869. var factorGradient1 = currentGradient;
  55870. var factorGradient2 = nextGradient;
  55871. var lifeTime1 = factorGradient1.getFactor();
  55872. var lifeTime2 = factorGradient2.getFactor();
  55873. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55874. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55875. });
  55876. }
  55877. else {
  55878. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55879. }
  55880. // Size
  55881. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55882. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55883. }
  55884. else {
  55885. particle._currentSizeGradient = this_1._sizeGradients[0];
  55886. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55887. particle.size = particle._currentSize1;
  55888. if (this_1._sizeGradients.length > 1) {
  55889. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55890. }
  55891. else {
  55892. particle._currentSize2 = particle._currentSize1;
  55893. }
  55894. }
  55895. // Size and scale
  55896. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55897. // Angle
  55898. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55899. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55900. }
  55901. else {
  55902. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55903. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55904. particle._currentAngularSpeed1 = particle.angularSpeed;
  55905. if (this_1._angularSpeedGradients.length > 1) {
  55906. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55907. }
  55908. else {
  55909. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55910. }
  55911. }
  55912. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55913. // Velocity
  55914. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  55915. particle._currentVelocityGradient = this_1._velocityGradients[0];
  55916. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  55917. if (this_1._velocityGradients.length > 1) {
  55918. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  55919. }
  55920. else {
  55921. particle._currentVelocity2 = particle._currentVelocity1;
  55922. }
  55923. }
  55924. // Color
  55925. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55926. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55927. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55928. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55929. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55930. }
  55931. else {
  55932. particle._currentColorGradient = this_1._colorGradients[0];
  55933. particle._currentColorGradient.getColorToRef(particle.color);
  55934. particle._currentColor1.copyFrom(particle.color);
  55935. if (this_1._colorGradients.length > 1) {
  55936. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55937. }
  55938. else {
  55939. particle._currentColor2.copyFrom(particle.color);
  55940. }
  55941. }
  55942. // Sheet
  55943. if (this_1._isAnimationSheetEnabled) {
  55944. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55945. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55946. }
  55947. };
  55948. var this_1 = this, step;
  55949. for (var index = 0; index < newParticles; index++) {
  55950. var state_1 = _loop_2();
  55951. if (state_1 === "break")
  55952. break;
  55953. }
  55954. };
  55955. /** @hidden */
  55956. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55957. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55958. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55959. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55960. if (isAnimationSheetEnabled) {
  55961. attributeNamesOrOptions.push("cellIndex");
  55962. }
  55963. if (!isBillboardBased) {
  55964. attributeNamesOrOptions.push("direction");
  55965. }
  55966. return attributeNamesOrOptions;
  55967. };
  55968. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55969. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55970. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55971. if (isAnimationSheetEnabled) {
  55972. effectCreationOption.push("particlesInfos");
  55973. }
  55974. return effectCreationOption;
  55975. };
  55976. ParticleSystem.prototype._getEffect = function () {
  55977. if (this._customEffect) {
  55978. return this._customEffect;
  55979. }
  55980. ;
  55981. var defines = [];
  55982. if (this._scene.clipPlane) {
  55983. defines.push("#define CLIPPLANE");
  55984. }
  55985. if (this._isAnimationSheetEnabled) {
  55986. defines.push("#define ANIMATESHEET");
  55987. }
  55988. if (this._isBillboardBased) {
  55989. defines.push("#define BILLBOARD");
  55990. switch (this.billboardMode) {
  55991. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55992. defines.push("#define BILLBOARDY");
  55993. break;
  55994. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55995. default:
  55996. break;
  55997. }
  55998. }
  55999. // Effect
  56000. var join = defines.join("\n");
  56001. if (this._cachedDefines !== join) {
  56002. this._cachedDefines = join;
  56003. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56004. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56005. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56006. }
  56007. return this._effect;
  56008. };
  56009. /**
  56010. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56011. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56012. */
  56013. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56014. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56015. if (!this._started)
  56016. return;
  56017. if (!preWarmOnly) {
  56018. var effect = this._getEffect();
  56019. // Check
  56020. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56021. return;
  56022. if (this._currentRenderId === this._scene.getRenderId()) {
  56023. return;
  56024. }
  56025. this._currentRenderId = this._scene.getRenderId();
  56026. }
  56027. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56028. // determine the number of particles we need to create
  56029. var newParticles;
  56030. if (this.manualEmitCount > -1) {
  56031. newParticles = this.manualEmitCount;
  56032. this._newPartsExcess = 0;
  56033. this.manualEmitCount = 0;
  56034. }
  56035. else {
  56036. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56037. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56038. }
  56039. if (this._newPartsExcess > 1.0) {
  56040. newParticles += this._newPartsExcess >> 0;
  56041. this._newPartsExcess -= this._newPartsExcess >> 0;
  56042. }
  56043. this._alive = false;
  56044. if (!this._stopped) {
  56045. this._actualFrame += this._scaledUpdateSpeed;
  56046. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56047. this.stop();
  56048. }
  56049. else {
  56050. newParticles = 0;
  56051. }
  56052. this._update(newParticles);
  56053. // Stopped?
  56054. if (this._stopped) {
  56055. if (!this._alive) {
  56056. this._started = false;
  56057. if (this.onAnimationEnd) {
  56058. this.onAnimationEnd();
  56059. }
  56060. if (this.disposeOnStop) {
  56061. this._scene._toBeDisposed.push(this);
  56062. }
  56063. }
  56064. }
  56065. if (!preWarmOnly) {
  56066. // Update VBO
  56067. var offset = 0;
  56068. for (var index = 0; index < this._particles.length; index++) {
  56069. var particle = this._particles[index];
  56070. this._appendParticleVertices(offset, particle);
  56071. offset += this._useInstancing ? 1 : 4;
  56072. }
  56073. if (this._vertexBuffer) {
  56074. this._vertexBuffer.update(this._vertexData);
  56075. }
  56076. }
  56077. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56078. this.stop();
  56079. }
  56080. };
  56081. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56082. this._appendParticleVertex(offset++, particle, 0, 0);
  56083. if (!this._useInstancing) {
  56084. this._appendParticleVertex(offset++, particle, 1, 0);
  56085. this._appendParticleVertex(offset++, particle, 1, 1);
  56086. this._appendParticleVertex(offset++, particle, 0, 1);
  56087. }
  56088. };
  56089. /**
  56090. * Rebuilds the particle system.
  56091. */
  56092. ParticleSystem.prototype.rebuild = function () {
  56093. this._createIndexBuffer();
  56094. if (this._vertexBuffer) {
  56095. this._vertexBuffer._rebuild();
  56096. }
  56097. };
  56098. /**
  56099. * Is this system ready to be used/rendered
  56100. * @return true if the system is ready
  56101. */
  56102. ParticleSystem.prototype.isReady = function () {
  56103. var effect = this._getEffect();
  56104. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56105. return false;
  56106. }
  56107. return true;
  56108. };
  56109. /**
  56110. * Renders the particle system in its current state.
  56111. * @returns the current number of particles
  56112. */
  56113. ParticleSystem.prototype.render = function () {
  56114. var effect = this._getEffect();
  56115. // Check
  56116. if (!this.isReady() || !this._particles.length) {
  56117. return 0;
  56118. }
  56119. var engine = this._scene.getEngine();
  56120. // Render
  56121. engine.enableEffect(effect);
  56122. engine.setState(false);
  56123. var viewMatrix = this._scene.getViewMatrix();
  56124. effect.setTexture("diffuseSampler", this.particleTexture);
  56125. effect.setMatrix("view", viewMatrix);
  56126. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56127. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56128. var baseSize = this.particleTexture.getBaseSize();
  56129. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56130. }
  56131. effect.setVector2("translationPivot", this.translationPivot);
  56132. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56133. if (this._isBillboardBased) {
  56134. var camera = this._scene.activeCamera;
  56135. effect.setVector3("eyePosition", camera.globalPosition);
  56136. }
  56137. if (this._scene.clipPlane) {
  56138. var clipPlane = this._scene.clipPlane;
  56139. var invView = viewMatrix.clone();
  56140. invView.invert();
  56141. effect.setMatrix("invView", invView);
  56142. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56143. }
  56144. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56145. // Draw order
  56146. switch (this.blendMode) {
  56147. case ParticleSystem.BLENDMODE_ADD:
  56148. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56149. break;
  56150. case ParticleSystem.BLENDMODE_ONEONE:
  56151. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56152. break;
  56153. case ParticleSystem.BLENDMODE_STANDARD:
  56154. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56155. break;
  56156. }
  56157. if (this.forceDepthWrite) {
  56158. engine.setDepthWrite(true);
  56159. }
  56160. if (this._useInstancing) {
  56161. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56162. engine.unbindInstanceAttributes();
  56163. }
  56164. else {
  56165. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56166. }
  56167. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56168. return this._particles.length;
  56169. };
  56170. /**
  56171. * Disposes the particle system and free the associated resources
  56172. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56173. */
  56174. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56175. if (disposeTexture === void 0) { disposeTexture = true; }
  56176. if (this._vertexBuffer) {
  56177. this._vertexBuffer.dispose();
  56178. this._vertexBuffer = null;
  56179. }
  56180. if (this._spriteBuffer) {
  56181. this._spriteBuffer.dispose();
  56182. this._spriteBuffer = null;
  56183. }
  56184. if (this._indexBuffer) {
  56185. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56186. this._indexBuffer = null;
  56187. }
  56188. if (disposeTexture && this.particleTexture) {
  56189. this.particleTexture.dispose();
  56190. this.particleTexture = null;
  56191. }
  56192. this._removeFromRoot();
  56193. // Remove from scene
  56194. var index = this._scene.particleSystems.indexOf(this);
  56195. if (index > -1) {
  56196. this._scene.particleSystems.splice(index, 1);
  56197. }
  56198. // Callback
  56199. this.onDisposeObservable.notifyObservers(this);
  56200. this.onDisposeObservable.clear();
  56201. };
  56202. /**
  56203. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56204. * @param radius The radius of the sphere to emit from
  56205. * @returns the emitter
  56206. */
  56207. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56208. if (radius === void 0) { radius = 1; }
  56209. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56210. this.particleEmitterType = particleEmitter;
  56211. return particleEmitter;
  56212. };
  56213. /**
  56214. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56215. * @param radius The radius of the sphere to emit from
  56216. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56217. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56218. * @returns the emitter
  56219. */
  56220. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56221. if (radius === void 0) { radius = 1; }
  56222. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56223. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56224. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56225. this.particleEmitterType = particleEmitter;
  56226. return particleEmitter;
  56227. };
  56228. /**
  56229. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56230. * @param radius The radius of the cone to emit from
  56231. * @param angle The base angle of the cone
  56232. * @returns the emitter
  56233. */
  56234. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56235. if (radius === void 0) { radius = 1; }
  56236. if (angle === void 0) { angle = Math.PI / 4; }
  56237. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56238. this.particleEmitterType = particleEmitter;
  56239. return particleEmitter;
  56240. };
  56241. // 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.
  56242. /**
  56243. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56244. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56245. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56246. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56247. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56248. * @returns the emitter
  56249. */
  56250. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56251. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56252. this.particleEmitterType = particleEmitter;
  56253. this.direction1 = direction1;
  56254. this.direction2 = direction2;
  56255. this.minEmitBox = minEmitBox;
  56256. this.maxEmitBox = maxEmitBox;
  56257. return particleEmitter;
  56258. };
  56259. // Clone
  56260. /**
  56261. * Clones the particle system.
  56262. * @param name The name of the cloned object
  56263. * @param newEmitter The new emitter to use
  56264. * @returns the cloned particle system
  56265. */
  56266. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56267. var custom = null;
  56268. var program = null;
  56269. if (this.customShader != null) {
  56270. program = this.customShader;
  56271. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56272. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56273. }
  56274. else if (this._customEffect) {
  56275. custom = this._customEffect;
  56276. }
  56277. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56278. result.customShader = program;
  56279. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56280. if (newEmitter === undefined) {
  56281. newEmitter = this.emitter;
  56282. }
  56283. result.emitter = newEmitter;
  56284. if (this.particleTexture) {
  56285. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56286. }
  56287. if (!this.preventAutoStart) {
  56288. result.start();
  56289. }
  56290. return result;
  56291. };
  56292. /**
  56293. * Serializes the particle system to a JSON object.
  56294. * @returns the JSON object
  56295. */
  56296. ParticleSystem.prototype.serialize = function () {
  56297. var serializationObject = {};
  56298. ParticleSystem._Serialize(serializationObject, this);
  56299. serializationObject.textureMask = this.textureMask.asArray();
  56300. serializationObject.customShader = this.customShader;
  56301. serializationObject.preventAutoStart = this.preventAutoStart;
  56302. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56303. return serializationObject;
  56304. };
  56305. /** @hidden */
  56306. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56307. serializationObject.name = particleSystem.name;
  56308. serializationObject.id = particleSystem.id;
  56309. serializationObject.capacity = particleSystem.getCapacity();
  56310. // Emitter
  56311. if (particleSystem.emitter.position) {
  56312. var emitterMesh = particleSystem.emitter;
  56313. serializationObject.emitterId = emitterMesh.id;
  56314. }
  56315. else {
  56316. var emitterPosition = particleSystem.emitter;
  56317. serializationObject.emitter = emitterPosition.asArray();
  56318. }
  56319. // Emitter
  56320. if (particleSystem.particleEmitterType) {
  56321. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56322. }
  56323. if (particleSystem.particleTexture) {
  56324. serializationObject.textureName = particleSystem.particleTexture.name;
  56325. }
  56326. // Animations
  56327. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56328. // Particle system
  56329. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56330. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56331. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56332. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56333. serializationObject.minSize = particleSystem.minSize;
  56334. serializationObject.maxSize = particleSystem.maxSize;
  56335. serializationObject.minScaleX = particleSystem.minScaleX;
  56336. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56337. serializationObject.minScaleY = particleSystem.minScaleY;
  56338. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56339. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56340. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56341. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56342. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56343. serializationObject.emitRate = particleSystem.emitRate;
  56344. serializationObject.gravity = particleSystem.gravity.asArray();
  56345. serializationObject.color1 = particleSystem.color1.asArray();
  56346. serializationObject.color2 = particleSystem.color2.asArray();
  56347. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56348. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56349. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56350. serializationObject.blendMode = particleSystem.blendMode;
  56351. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56352. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56353. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56354. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56355. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56356. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56357. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56358. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56359. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56360. var colorGradients = particleSystem.getColorGradients();
  56361. if (colorGradients) {
  56362. serializationObject.colorGradients = [];
  56363. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56364. var colorGradient = colorGradients_1[_i];
  56365. var serializedGradient = {
  56366. gradient: colorGradient.gradient,
  56367. color1: colorGradient.color1.asArray()
  56368. };
  56369. if (colorGradient.color2) {
  56370. serializedGradient.color2 = colorGradient.color2.asArray();
  56371. }
  56372. serializationObject.colorGradients.push(serializedGradient);
  56373. }
  56374. }
  56375. var sizeGradients = particleSystem.getSizeGradients();
  56376. if (sizeGradients) {
  56377. serializationObject.sizeGradients = [];
  56378. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56379. var sizeGradient = sizeGradients_1[_a];
  56380. var serializedGradient = {
  56381. gradient: sizeGradient.gradient,
  56382. factor1: sizeGradient.factor1
  56383. };
  56384. if (sizeGradient.factor2 !== undefined) {
  56385. serializedGradient.factor2 = sizeGradient.factor2;
  56386. }
  56387. serializationObject.sizeGradients.push(serializedGradient);
  56388. }
  56389. }
  56390. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56391. if (angularSpeedGradients) {
  56392. serializationObject.angularSpeedGradients = [];
  56393. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56394. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56395. var serializedGradient = {
  56396. gradient: angularSpeedGradient.gradient,
  56397. factor1: angularSpeedGradient.factor1
  56398. };
  56399. if (angularSpeedGradient.factor2 !== undefined) {
  56400. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56401. }
  56402. serializationObject.angularSpeedGradients.push(serializedGradient);
  56403. }
  56404. }
  56405. var velocityGradients = particleSystem.getVelocityGradients();
  56406. if (velocityGradients) {
  56407. serializationObject.velocityGradients = [];
  56408. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  56409. var velocityGradient = velocityGradients_1[_c];
  56410. var serializedGradient = {
  56411. gradient: velocityGradient.gradient,
  56412. factor1: velocityGradient.factor1
  56413. };
  56414. if (velocityGradient.factor2 !== undefined) {
  56415. serializedGradient.factor2 = velocityGradient.factor2;
  56416. }
  56417. serializationObject.velocityGradients.push(serializedGradient);
  56418. }
  56419. }
  56420. };
  56421. /** @hidden */
  56422. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56423. // Texture
  56424. if (parsedParticleSystem.textureName) {
  56425. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56426. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56427. }
  56428. // Emitter
  56429. if (parsedParticleSystem.emitterId === undefined) {
  56430. particleSystem.emitter = BABYLON.Vector3.Zero();
  56431. }
  56432. else if (parsedParticleSystem.emitterId) {
  56433. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56434. }
  56435. else {
  56436. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56437. }
  56438. // Misc.
  56439. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56440. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56441. }
  56442. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56443. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56444. }
  56445. // Animations
  56446. if (parsedParticleSystem.animations) {
  56447. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56448. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56449. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56450. }
  56451. }
  56452. if (parsedParticleSystem.autoAnimate) {
  56453. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56454. }
  56455. // Particle system
  56456. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56457. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56458. particleSystem.minSize = parsedParticleSystem.minSize;
  56459. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56460. if (parsedParticleSystem.minScaleX) {
  56461. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56462. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56463. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56464. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56465. }
  56466. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56467. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56468. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56469. }
  56470. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56471. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56472. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56473. }
  56474. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56475. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56476. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56477. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56478. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56479. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56480. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56481. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56482. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56483. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56484. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56485. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56486. if (parsedParticleSystem.colorGradients) {
  56487. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56488. var colorGradient = _a[_i];
  56489. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56490. }
  56491. }
  56492. if (parsedParticleSystem.sizeGradients) {
  56493. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56494. var sizeGradient = _c[_b];
  56495. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56496. }
  56497. }
  56498. if (parsedParticleSystem.angularSpeedGradients) {
  56499. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56500. var angularSpeedGradient = _e[_d];
  56501. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56502. }
  56503. }
  56504. if (parsedParticleSystem.velocityGradients) {
  56505. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  56506. var velocityGradient = _g[_f];
  56507. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  56508. }
  56509. }
  56510. // Emitter
  56511. var emitterType;
  56512. if (parsedParticleSystem.particleEmitterType) {
  56513. switch (parsedParticleSystem.particleEmitterType.type) {
  56514. case "SphereParticleEmitter":
  56515. emitterType = new BABYLON.SphereParticleEmitter();
  56516. break;
  56517. case "SphereDirectedParticleEmitter":
  56518. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56519. break;
  56520. case "ConeEmitter":
  56521. case "ConeParticleEmitter":
  56522. emitterType = new BABYLON.ConeParticleEmitter();
  56523. break;
  56524. case "BoxEmitter":
  56525. case "BoxParticleEmitter":
  56526. default:
  56527. emitterType = new BABYLON.BoxParticleEmitter();
  56528. break;
  56529. }
  56530. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56531. }
  56532. else {
  56533. emitterType = new BABYLON.BoxParticleEmitter();
  56534. emitterType.parse(parsedParticleSystem);
  56535. }
  56536. particleSystem.particleEmitterType = emitterType;
  56537. // Animation sheet
  56538. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56539. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56540. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56541. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56542. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56543. };
  56544. /**
  56545. * Parses a JSON object to create a particle system.
  56546. * @param parsedParticleSystem The JSON object to parse
  56547. * @param scene The scene to create the particle system in
  56548. * @param rootUrl The root url to use to load external dependencies like texture
  56549. * @returns the Parsed particle system
  56550. */
  56551. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56552. var name = parsedParticleSystem.name;
  56553. var custom = null;
  56554. var program = null;
  56555. if (parsedParticleSystem.customShader) {
  56556. program = parsedParticleSystem.customShader;
  56557. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56558. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56559. }
  56560. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56561. particleSystem.customShader = program;
  56562. if (parsedParticleSystem.id) {
  56563. particleSystem.id = parsedParticleSystem.id;
  56564. }
  56565. // Auto start
  56566. if (parsedParticleSystem.preventAutoStart) {
  56567. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56568. }
  56569. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56570. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56571. if (!particleSystem.preventAutoStart) {
  56572. particleSystem.start();
  56573. }
  56574. return particleSystem;
  56575. };
  56576. /**
  56577. * Source color is added to the destination color without alpha affecting the result.
  56578. */
  56579. ParticleSystem.BLENDMODE_ONEONE = 0;
  56580. /**
  56581. * Blend current color and particle color using particle’s alpha.
  56582. */
  56583. ParticleSystem.BLENDMODE_STANDARD = 1;
  56584. /**
  56585. * Add current color and particle color multiplied by particle’s alpha.
  56586. */
  56587. ParticleSystem.BLENDMODE_ADD = 2;
  56588. return ParticleSystem;
  56589. }());
  56590. BABYLON.ParticleSystem = ParticleSystem;
  56591. })(BABYLON || (BABYLON = {}));
  56592. //# sourceMappingURL=babylon.particleSystem.js.map
  56593. var BABYLON;
  56594. (function (BABYLON) {
  56595. /**
  56596. * Particle emitter emitting particles from the inside of a box.
  56597. * It emits the particles randomly between 2 given directions.
  56598. */
  56599. var BoxParticleEmitter = /** @class */ (function () {
  56600. /**
  56601. * Creates a new instance BoxParticleEmitter
  56602. */
  56603. function BoxParticleEmitter() {
  56604. /**
  56605. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56606. */
  56607. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56608. /**
  56609. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56610. */
  56611. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56612. /**
  56613. * 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.
  56614. */
  56615. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56616. /**
  56617. * 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.
  56618. */
  56619. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56620. }
  56621. /**
  56622. * Called by the particle System when the direction is computed for the created particle.
  56623. * @param worldMatrix is the world matrix of the particle system
  56624. * @param directionToUpdate is the direction vector to update with the result
  56625. * @param particle is the particle we are computed the direction for
  56626. */
  56627. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56628. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56629. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56630. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56631. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56632. };
  56633. /**
  56634. * Called by the particle System when the position is computed for the created particle.
  56635. * @param worldMatrix is the world matrix of the particle system
  56636. * @param positionToUpdate is the position vector to update with the result
  56637. * @param particle is the particle we are computed the position for
  56638. */
  56639. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56640. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56641. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56642. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56643. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56644. };
  56645. /**
  56646. * Clones the current emitter and returns a copy of it
  56647. * @returns the new emitter
  56648. */
  56649. BoxParticleEmitter.prototype.clone = function () {
  56650. var newOne = new BoxParticleEmitter();
  56651. BABYLON.Tools.DeepCopy(this, newOne);
  56652. return newOne;
  56653. };
  56654. /**
  56655. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56656. * @param effect defines the update shader
  56657. */
  56658. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56659. effect.setVector3("direction1", this.direction1);
  56660. effect.setVector3("direction2", this.direction2);
  56661. effect.setVector3("minEmitBox", this.minEmitBox);
  56662. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56663. };
  56664. /**
  56665. * Returns a string to use to update the GPU particles update shader
  56666. * @returns a string containng the defines string
  56667. */
  56668. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56669. return "#define BOXEMITTER";
  56670. };
  56671. /**
  56672. * Returns the string "BoxParticleEmitter"
  56673. * @returns a string containing the class name
  56674. */
  56675. BoxParticleEmitter.prototype.getClassName = function () {
  56676. return "BoxParticleEmitter";
  56677. };
  56678. /**
  56679. * Serializes the particle system to a JSON object.
  56680. * @returns the JSON object
  56681. */
  56682. BoxParticleEmitter.prototype.serialize = function () {
  56683. var serializationObject = {};
  56684. serializationObject.type = this.getClassName();
  56685. serializationObject.direction1 = this.direction1.asArray();
  56686. serializationObject.direction2 = this.direction2.asArray();
  56687. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56688. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56689. return serializationObject;
  56690. };
  56691. /**
  56692. * Parse properties from a JSON object
  56693. * @param serializationObject defines the JSON object
  56694. */
  56695. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56696. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56697. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56698. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56699. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56700. };
  56701. return BoxParticleEmitter;
  56702. }());
  56703. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56704. })(BABYLON || (BABYLON = {}));
  56705. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56706. var BABYLON;
  56707. (function (BABYLON) {
  56708. /**
  56709. * Particle emitter emitting particles from the inside of a cone.
  56710. * It emits the particles alongside the cone volume from the base to the particle.
  56711. * The emission direction might be randomized.
  56712. */
  56713. var ConeParticleEmitter = /** @class */ (function () {
  56714. /**
  56715. * Creates a new instance ConeParticleEmitter
  56716. * @param radius the radius of the emission cone (1 by default)
  56717. * @param angles the cone base angle (PI by default)
  56718. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56719. */
  56720. function ConeParticleEmitter(radius, angle,
  56721. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56722. directionRandomizer) {
  56723. if (radius === void 0) { radius = 1; }
  56724. if (angle === void 0) { angle = Math.PI; }
  56725. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56726. this.directionRandomizer = directionRandomizer;
  56727. /**
  56728. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56729. */
  56730. this.radiusRange = 1;
  56731. /**
  56732. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56733. */
  56734. this.heightRange = 1;
  56735. this.angle = angle;
  56736. this.radius = radius;
  56737. }
  56738. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56739. /**
  56740. * Gets or sets the radius of the emission cone
  56741. */
  56742. get: function () {
  56743. return this._radius;
  56744. },
  56745. set: function (value) {
  56746. this._radius = value;
  56747. this._buildHeight();
  56748. },
  56749. enumerable: true,
  56750. configurable: true
  56751. });
  56752. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56753. /**
  56754. * Gets or sets the angle of the emission cone
  56755. */
  56756. get: function () {
  56757. return this._angle;
  56758. },
  56759. set: function (value) {
  56760. this._angle = value;
  56761. this._buildHeight();
  56762. },
  56763. enumerable: true,
  56764. configurable: true
  56765. });
  56766. ConeParticleEmitter.prototype._buildHeight = function () {
  56767. if (this._angle !== 0) {
  56768. this._height = this._radius / Math.tan(this._angle / 2);
  56769. }
  56770. else {
  56771. this._height = 1;
  56772. }
  56773. };
  56774. /**
  56775. * Called by the particle System when the direction is computed for the created particle.
  56776. * @param worldMatrix is the world matrix of the particle system
  56777. * @param directionToUpdate is the direction vector to update with the result
  56778. * @param particle is the particle we are computed the direction for
  56779. */
  56780. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56781. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56782. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56783. }
  56784. else {
  56785. // measure the direction Vector from the emitter to the particle.
  56786. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56787. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56788. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56789. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56790. direction.x += randX;
  56791. direction.y += randY;
  56792. direction.z += randZ;
  56793. direction.normalize();
  56794. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56795. }
  56796. };
  56797. /**
  56798. * Called by the particle System when the position is computed for the created particle.
  56799. * @param worldMatrix is the world matrix of the particle system
  56800. * @param positionToUpdate is the position vector to update with the result
  56801. * @param particle is the particle we are computed the position for
  56802. */
  56803. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56804. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56805. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56806. // Better distribution in a cone at normal angles.
  56807. h = 1 - h * h;
  56808. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56809. radius = radius * h;
  56810. var randX = radius * Math.sin(s);
  56811. var randZ = radius * Math.cos(s);
  56812. var randY = h * this._height;
  56813. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56814. };
  56815. /**
  56816. * Clones the current emitter and returns a copy of it
  56817. * @returns the new emitter
  56818. */
  56819. ConeParticleEmitter.prototype.clone = function () {
  56820. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56821. BABYLON.Tools.DeepCopy(this, newOne);
  56822. return newOne;
  56823. };
  56824. /**
  56825. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56826. * @param effect defines the update shader
  56827. */
  56828. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56829. effect.setFloat2("radius", this._radius, this.radiusRange);
  56830. effect.setFloat("coneAngle", this._angle);
  56831. effect.setFloat2("height", this._height, this.heightRange);
  56832. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56833. };
  56834. /**
  56835. * Returns a string to use to update the GPU particles update shader
  56836. * @returns a string containng the defines string
  56837. */
  56838. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56839. return "#define CONEEMITTER";
  56840. };
  56841. /**
  56842. * Returns the string "ConeParticleEmitter"
  56843. * @returns a string containing the class name
  56844. */
  56845. ConeParticleEmitter.prototype.getClassName = function () {
  56846. return "ConeParticleEmitter";
  56847. };
  56848. /**
  56849. * Serializes the particle system to a JSON object.
  56850. * @returns the JSON object
  56851. */
  56852. ConeParticleEmitter.prototype.serialize = function () {
  56853. var serializationObject = {};
  56854. serializationObject.type = this.getClassName();
  56855. serializationObject.radius = this._radius;
  56856. serializationObject.angle = this._angle;
  56857. serializationObject.directionRandomizer = this.directionRandomizer;
  56858. return serializationObject;
  56859. };
  56860. /**
  56861. * Parse properties from a JSON object
  56862. * @param serializationObject defines the JSON object
  56863. */
  56864. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56865. this.radius = serializationObject.radius;
  56866. this.angle = serializationObject.angle;
  56867. this.directionRandomizer = serializationObject.directionRandomizer;
  56868. };
  56869. return ConeParticleEmitter;
  56870. }());
  56871. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56872. })(BABYLON || (BABYLON = {}));
  56873. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56874. var BABYLON;
  56875. (function (BABYLON) {
  56876. /**
  56877. * Particle emitter emitting particles from the inside of a sphere.
  56878. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56879. */
  56880. var SphereParticleEmitter = /** @class */ (function () {
  56881. /**
  56882. * Creates a new instance SphereParticleEmitter
  56883. * @param radius the radius of the emission sphere (1 by default)
  56884. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56885. */
  56886. function SphereParticleEmitter(
  56887. /**
  56888. * The radius of the emission sphere.
  56889. */
  56890. radius,
  56891. /**
  56892. * How much to randomize the particle direction [0-1].
  56893. */
  56894. directionRandomizer) {
  56895. if (radius === void 0) { radius = 1; }
  56896. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56897. this.radius = radius;
  56898. this.directionRandomizer = directionRandomizer;
  56899. /**
  56900. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56901. */
  56902. this.radiusRange = 1;
  56903. }
  56904. /**
  56905. * Called by the particle System when the direction is computed for the created particle.
  56906. * @param worldMatrix is the world matrix of the particle system
  56907. * @param directionToUpdate is the direction vector to update with the result
  56908. * @param particle is the particle we are computed the direction for
  56909. */
  56910. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56911. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56912. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56913. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56914. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56915. direction.x += randX;
  56916. direction.y += randY;
  56917. direction.z += randZ;
  56918. direction.normalize();
  56919. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56920. };
  56921. /**
  56922. * Called by the particle System when the position is computed for the created particle.
  56923. * @param worldMatrix is the world matrix of the particle system
  56924. * @param positionToUpdate is the position vector to update with the result
  56925. * @param particle is the particle we are computed the position for
  56926. */
  56927. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56928. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56929. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56930. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56931. var theta = Math.acos(2 * v - 1);
  56932. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56933. var randY = randRadius * Math.cos(theta);
  56934. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56935. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56936. };
  56937. /**
  56938. * Clones the current emitter and returns a copy of it
  56939. * @returns the new emitter
  56940. */
  56941. SphereParticleEmitter.prototype.clone = function () {
  56942. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56943. BABYLON.Tools.DeepCopy(this, newOne);
  56944. return newOne;
  56945. };
  56946. /**
  56947. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56948. * @param effect defines the update shader
  56949. */
  56950. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56951. effect.setFloat("radius", this.radius);
  56952. effect.setFloat("radiusRange", this.radiusRange);
  56953. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56954. };
  56955. /**
  56956. * Returns a string to use to update the GPU particles update shader
  56957. * @returns a string containng the defines string
  56958. */
  56959. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56960. return "#define SPHEREEMITTER";
  56961. };
  56962. /**
  56963. * Returns the string "SphereParticleEmitter"
  56964. * @returns a string containing the class name
  56965. */
  56966. SphereParticleEmitter.prototype.getClassName = function () {
  56967. return "SphereParticleEmitter";
  56968. };
  56969. /**
  56970. * Serializes the particle system to a JSON object.
  56971. * @returns the JSON object
  56972. */
  56973. SphereParticleEmitter.prototype.serialize = function () {
  56974. var serializationObject = {};
  56975. serializationObject.type = this.getClassName();
  56976. serializationObject.radius = this.radius;
  56977. serializationObject.radiusRange = this.radiusRange;
  56978. serializationObject.directionRandomizer = this.directionRandomizer;
  56979. return serializationObject;
  56980. };
  56981. /**
  56982. * Parse properties from a JSON object
  56983. * @param serializationObject defines the JSON object
  56984. */
  56985. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56986. this.radius = serializationObject.radius;
  56987. this.radiusRange = serializationObject.radiusRange;
  56988. this.directionRandomizer = serializationObject.directionRandomizer;
  56989. };
  56990. return SphereParticleEmitter;
  56991. }());
  56992. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56993. /**
  56994. * Particle emitter emitting particles from the inside of a sphere.
  56995. * It emits the particles randomly between two vectors.
  56996. */
  56997. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56998. __extends(SphereDirectedParticleEmitter, _super);
  56999. /**
  57000. * Creates a new instance SphereDirectedParticleEmitter
  57001. * @param radius the radius of the emission sphere (1 by default)
  57002. * @param direction1 the min limit of the emission direction (up vector by default)
  57003. * @param direction2 the max limit of the emission direction (up vector by default)
  57004. */
  57005. function SphereDirectedParticleEmitter(radius,
  57006. /**
  57007. * The min limit of the emission direction.
  57008. */
  57009. direction1,
  57010. /**
  57011. * The max limit of the emission direction.
  57012. */
  57013. direction2) {
  57014. if (radius === void 0) { radius = 1; }
  57015. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57016. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57017. var _this = _super.call(this, radius) || this;
  57018. _this.direction1 = direction1;
  57019. _this.direction2 = direction2;
  57020. return _this;
  57021. }
  57022. /**
  57023. * Called by the particle System when the direction is computed for the created particle.
  57024. * @param worldMatrix is the world matrix of the particle system
  57025. * @param directionToUpdate is the direction vector to update with the result
  57026. * @param particle is the particle we are computed the direction for
  57027. */
  57028. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57029. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57030. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57031. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57032. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57033. };
  57034. /**
  57035. * Clones the current emitter and returns a copy of it
  57036. * @returns the new emitter
  57037. */
  57038. SphereDirectedParticleEmitter.prototype.clone = function () {
  57039. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57040. BABYLON.Tools.DeepCopy(this, newOne);
  57041. return newOne;
  57042. };
  57043. /**
  57044. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57045. * @param effect defines the update shader
  57046. */
  57047. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57048. effect.setFloat("radius", this.radius);
  57049. effect.setFloat("radiusRange", this.radiusRange);
  57050. effect.setVector3("direction1", this.direction1);
  57051. effect.setVector3("direction2", this.direction2);
  57052. };
  57053. /**
  57054. * Returns a string to use to update the GPU particles update shader
  57055. * @returns a string containng the defines string
  57056. */
  57057. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57058. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57059. };
  57060. /**
  57061. * Returns the string "SphereDirectedParticleEmitter"
  57062. * @returns a string containing the class name
  57063. */
  57064. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57065. return "SphereDirectedParticleEmitter";
  57066. };
  57067. /**
  57068. * Serializes the particle system to a JSON object.
  57069. * @returns the JSON object
  57070. */
  57071. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57072. var serializationObject = _super.prototype.serialize.call(this);
  57073. serializationObject.direction1 = this.direction1.asArray();
  57074. serializationObject.direction2 = this.direction2.asArray();
  57075. return serializationObject;
  57076. };
  57077. /**
  57078. * Parse properties from a JSON object
  57079. * @param serializationObject defines the JSON object
  57080. */
  57081. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57082. _super.prototype.parse.call(this, serializationObject);
  57083. this.direction1.copyFrom(serializationObject.direction1);
  57084. this.direction2.copyFrom(serializationObject.direction2);
  57085. };
  57086. return SphereDirectedParticleEmitter;
  57087. }(SphereParticleEmitter));
  57088. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57089. })(BABYLON || (BABYLON = {}));
  57090. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57091. var BABYLON;
  57092. (function (BABYLON) {
  57093. // Adds the parser to the scene parsers.
  57094. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  57095. // Particles Systems
  57096. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57097. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57098. var parsedParticleSystem = parsedData.particleSystems[index];
  57099. if (parsedParticleSystem.activeParticleCount) {
  57100. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57101. container.particleSystems.push(ps);
  57102. }
  57103. else {
  57104. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57105. container.particleSystems.push(ps);
  57106. }
  57107. }
  57108. }
  57109. });
  57110. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  57111. if (uniformsNames === void 0) { uniformsNames = []; }
  57112. if (samplers === void 0) { samplers = []; }
  57113. if (defines === void 0) { defines = ""; }
  57114. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  57115. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  57116. if (defines.indexOf(" BILLBOARD") === -1) {
  57117. defines += "\n#define BILLBOARD\n";
  57118. }
  57119. if (samplers.indexOf("diffuseSampler") === -1) {
  57120. samplers.push("diffuseSampler");
  57121. }
  57122. return this.createEffect({
  57123. vertex: "particles",
  57124. fragmentElement: fragmentName
  57125. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  57126. };
  57127. })(BABYLON || (BABYLON = {}));
  57128. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  57129. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57130. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57131. s = arguments[i];
  57132. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57133. t[p] = s[p];
  57134. }
  57135. return t;
  57136. };
  57137. var BABYLON;
  57138. (function (BABYLON) {
  57139. /**
  57140. * This represents a GPU particle system in Babylon
  57141. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57142. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57143. */
  57144. var GPUParticleSystem = /** @class */ (function () {
  57145. /**
  57146. * Instantiates a GPU particle system.
  57147. * 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.
  57148. * @param name The name of the particle system
  57149. * @param options The options used to create the system
  57150. * @param scene The scene the particle system belongs to
  57151. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57152. */
  57153. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  57154. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57155. /**
  57156. * The emitter represents the Mesh or position we are attaching the particle system to.
  57157. */
  57158. this.emitter = null;
  57159. /**
  57160. * The rendering group used by the Particle system to chose when to render.
  57161. */
  57162. this.renderingGroupId = 0;
  57163. /**
  57164. * The layer mask we are rendering the particles through.
  57165. */
  57166. this.layerMask = 0x0FFFFFFF;
  57167. this._accumulatedCount = 0;
  57168. this._targetIndex = 0;
  57169. this._currentRenderId = -1;
  57170. this._started = false;
  57171. this._stopped = false;
  57172. this._timeDelta = 0;
  57173. this._attributesStrideSize = 21;
  57174. this._actualFrame = 0;
  57175. this._rawTextureWidth = 256;
  57176. /**
  57177. * List of animations used by the particle system.
  57178. */
  57179. this.animations = [];
  57180. /**
  57181. * An event triggered when the system is disposed.
  57182. */
  57183. this.onDisposeObservable = new BABYLON.Observable();
  57184. /**
  57185. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57186. */
  57187. this.updateSpeed = 0.01;
  57188. /**
  57189. * The amount of time the particle system is running (depends of the overall update speed).
  57190. */
  57191. this.targetStopDuration = 0;
  57192. /**
  57193. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57194. */
  57195. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57196. /**
  57197. * Minimum life time of emitting particles.
  57198. */
  57199. this.minLifeTime = 1;
  57200. /**
  57201. * Maximum life time of emitting particles.
  57202. */
  57203. this.maxLifeTime = 1;
  57204. /**
  57205. * Minimum Size of emitting particles.
  57206. */
  57207. this.minSize = 1;
  57208. /**
  57209. * Maximum Size of emitting particles.
  57210. */
  57211. this.maxSize = 1;
  57212. /**
  57213. * Minimum scale of emitting particles on X axis.
  57214. */
  57215. this.minScaleX = 1;
  57216. /**
  57217. * Maximum scale of emitting particles on X axis.
  57218. */
  57219. this.maxScaleX = 1;
  57220. /**
  57221. * Minimum scale of emitting particles on Y axis.
  57222. */
  57223. this.minScaleY = 1;
  57224. /**
  57225. * Maximum scale of emitting particles on Y axis.
  57226. */
  57227. this.maxScaleY = 1;
  57228. /**
  57229. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57230. */
  57231. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57232. /**
  57233. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57234. */
  57235. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57236. /**
  57237. * Color the particle will have at the end of its lifetime.
  57238. */
  57239. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57240. /**
  57241. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57242. */
  57243. this.emitRate = 100;
  57244. /**
  57245. * You can use gravity if you want to give an orientation to your particles.
  57246. */
  57247. this.gravity = BABYLON.Vector3.Zero();
  57248. /**
  57249. * Minimum power of emitting particles.
  57250. */
  57251. this.minEmitPower = 1;
  57252. /**
  57253. * Maximum power of emitting particles.
  57254. */
  57255. this.maxEmitPower = 1;
  57256. /**
  57257. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57258. */
  57259. this.minAngularSpeed = 0;
  57260. /**
  57261. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57262. */
  57263. this.maxAngularSpeed = 0;
  57264. /**
  57265. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57266. * to override the particles.
  57267. */
  57268. this.forceDepthWrite = false;
  57269. this._preWarmDone = false;
  57270. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  57271. this.preWarmCycles = 0;
  57272. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57273. this.preWarmStepOffset = 1;
  57274. /**
  57275. * Gets or sets the minimal initial rotation in radians.
  57276. */
  57277. this.minInitialRotation = 0;
  57278. /**
  57279. * Gets or sets the maximal initial rotation in radians.
  57280. */
  57281. this.maxInitialRotation = 0;
  57282. /**
  57283. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  57284. */
  57285. this.spriteCellChangeSpeed = 1;
  57286. /**
  57287. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57288. */
  57289. this.startSpriteCellID = 0;
  57290. /**
  57291. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57292. */
  57293. this.endSpriteCellID = 0;
  57294. /**
  57295. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57296. */
  57297. this.spriteCellWidth = 0;
  57298. /**
  57299. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57300. */
  57301. this.spriteCellHeight = 0;
  57302. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57303. this.translationPivot = new BABYLON.Vector2(0, 0);
  57304. /**
  57305. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57306. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57307. */
  57308. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57309. this._isBillboardBased = true;
  57310. this._colorGradients = null;
  57311. this._angularSpeedGradients = null;
  57312. this._sizeGradients = null;
  57313. this._velocityGradients = null;
  57314. this.id = name;
  57315. this.name = name;
  57316. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57317. this._engine = this._scene.getEngine();
  57318. if (!options.randomTextureSize) {
  57319. delete options.randomTextureSize;
  57320. }
  57321. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57322. var optionsAsNumber = options;
  57323. if (isFinite(optionsAsNumber)) {
  57324. fullOptions.capacity = optionsAsNumber;
  57325. }
  57326. this._capacity = fullOptions.capacity;
  57327. this._activeCount = fullOptions.capacity;
  57328. this._currentActiveCount = 0;
  57329. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57330. this._scene.particleSystems.push(this);
  57331. this._updateEffectOptions = {
  57332. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57333. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57334. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57335. "angleRange", "radiusRange", "cellInfos"],
  57336. uniformBuffersNames: [],
  57337. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler"],
  57338. defines: "",
  57339. fallbacks: null,
  57340. onCompiled: null,
  57341. onError: null,
  57342. indexParameters: null,
  57343. maxSimultaneousLights: 0,
  57344. transformFeedbackVaryings: []
  57345. };
  57346. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57347. // Random data
  57348. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57349. var d = [];
  57350. for (var i = 0; i < maxTextureSize; ++i) {
  57351. d.push(Math.random());
  57352. d.push(Math.random());
  57353. d.push(Math.random());
  57354. d.push(Math.random());
  57355. }
  57356. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57357. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57358. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57359. d = [];
  57360. for (var i = 0; i < maxTextureSize; ++i) {
  57361. d.push(Math.random());
  57362. d.push(Math.random());
  57363. d.push(Math.random());
  57364. d.push(Math.random());
  57365. }
  57366. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57367. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57368. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57369. this._randomTextureSize = maxTextureSize;
  57370. }
  57371. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57372. /**
  57373. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57374. */
  57375. get: function () {
  57376. if (!BABYLON.Engine.LastCreatedEngine) {
  57377. return false;
  57378. }
  57379. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57380. },
  57381. enumerable: true,
  57382. configurable: true
  57383. });
  57384. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57385. /**
  57386. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57387. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57388. */
  57389. get: function () {
  57390. if (this.particleEmitterType.direction1) {
  57391. return this.particleEmitterType.direction1;
  57392. }
  57393. return BABYLON.Vector3.Zero();
  57394. },
  57395. set: function (value) {
  57396. if (this.particleEmitterType.direction1) {
  57397. this.particleEmitterType.direction1 = value;
  57398. }
  57399. },
  57400. enumerable: true,
  57401. configurable: true
  57402. });
  57403. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57404. /**
  57405. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57406. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57407. */
  57408. get: function () {
  57409. if (this.particleEmitterType.direction2) {
  57410. return this.particleEmitterType.direction2;
  57411. }
  57412. return BABYLON.Vector3.Zero();
  57413. },
  57414. set: function (value) {
  57415. if (this.particleEmitterType.direction2) {
  57416. this.particleEmitterType.direction2 = value;
  57417. }
  57418. },
  57419. enumerable: true,
  57420. configurable: true
  57421. });
  57422. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57423. /**
  57424. * 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.
  57425. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57426. */
  57427. get: function () {
  57428. if (this.particleEmitterType.minEmitBox) {
  57429. return this.particleEmitterType.minEmitBox;
  57430. }
  57431. return BABYLON.Vector3.Zero();
  57432. },
  57433. set: function (value) {
  57434. if (this.particleEmitterType.minEmitBox) {
  57435. this.particleEmitterType.minEmitBox = value;
  57436. }
  57437. },
  57438. enumerable: true,
  57439. configurable: true
  57440. });
  57441. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57442. /**
  57443. * 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.
  57444. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57445. */
  57446. get: function () {
  57447. if (this.particleEmitterType.maxEmitBox) {
  57448. return this.particleEmitterType.maxEmitBox;
  57449. }
  57450. return BABYLON.Vector3.Zero();
  57451. },
  57452. set: function (value) {
  57453. if (this.particleEmitterType.maxEmitBox) {
  57454. this.particleEmitterType.maxEmitBox = value;
  57455. }
  57456. },
  57457. enumerable: true,
  57458. configurable: true
  57459. });
  57460. /**
  57461. * Gets the maximum number of particles active at the same time.
  57462. * @returns The max number of active particles.
  57463. */
  57464. GPUParticleSystem.prototype.getCapacity = function () {
  57465. return this._capacity;
  57466. };
  57467. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57468. /**
  57469. * Gets or set the number of active particles
  57470. */
  57471. get: function () {
  57472. return this._activeCount;
  57473. },
  57474. set: function (value) {
  57475. this._activeCount = Math.min(value, this._capacity);
  57476. },
  57477. enumerable: true,
  57478. configurable: true
  57479. });
  57480. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57481. /**
  57482. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57483. */
  57484. get: function () {
  57485. return this._isAnimationSheetEnabled;
  57486. },
  57487. enumerable: true,
  57488. configurable: true
  57489. });
  57490. /**
  57491. * Is this system ready to be used/rendered
  57492. * @return true if the system is ready
  57493. */
  57494. GPUParticleSystem.prototype.isReady = function () {
  57495. if (!this._updateEffect) {
  57496. this._recreateUpdateEffect();
  57497. this._recreateRenderEffect();
  57498. return false;
  57499. }
  57500. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57501. return false;
  57502. }
  57503. return true;
  57504. };
  57505. /**
  57506. * Gets Wether the system has been started.
  57507. * @returns True if it has been started, otherwise false.
  57508. */
  57509. GPUParticleSystem.prototype.isStarted = function () {
  57510. return this._started;
  57511. };
  57512. /**
  57513. * Starts the particle system and begins to emit.
  57514. */
  57515. GPUParticleSystem.prototype.start = function () {
  57516. this._started = true;
  57517. this._stopped = false;
  57518. this._preWarmDone = false;
  57519. };
  57520. /**
  57521. * Stops the particle system.
  57522. */
  57523. GPUParticleSystem.prototype.stop = function () {
  57524. this._stopped = true;
  57525. };
  57526. /**
  57527. * Remove all active particles
  57528. */
  57529. GPUParticleSystem.prototype.reset = function () {
  57530. this._releaseBuffers();
  57531. this._releaseVAOs();
  57532. this._currentActiveCount = 0;
  57533. this._targetIndex = 0;
  57534. };
  57535. /**
  57536. * Returns the string "GPUParticleSystem"
  57537. * @returns a string containing the class name
  57538. */
  57539. GPUParticleSystem.prototype.getClassName = function () {
  57540. return "GPUParticleSystem";
  57541. };
  57542. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57543. /**
  57544. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57545. */
  57546. get: function () {
  57547. return this._isBillboardBased;
  57548. },
  57549. set: function (value) {
  57550. if (this._isBillboardBased === value) {
  57551. return;
  57552. }
  57553. this._isBillboardBased = value;
  57554. this._releaseBuffers();
  57555. },
  57556. enumerable: true,
  57557. configurable: true
  57558. });
  57559. /**
  57560. * Gets the current list of color gradients.
  57561. * You must use addColorGradient and removeColorGradient to udpate this list
  57562. * @returns the list of color gradients
  57563. */
  57564. GPUParticleSystem.prototype.getColorGradients = function () {
  57565. return this._colorGradients;
  57566. };
  57567. /**
  57568. * Gets the current list of size gradients.
  57569. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57570. * @returns the list of size gradients
  57571. */
  57572. GPUParticleSystem.prototype.getSizeGradients = function () {
  57573. return this._sizeGradients;
  57574. };
  57575. /**
  57576. * Gets the current list of angular speed gradients.
  57577. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  57578. * @returns the list of angular speed gradients
  57579. */
  57580. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57581. return this._angularSpeedGradients;
  57582. };
  57583. /**
  57584. * Gets the current list of velocity gradients.
  57585. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  57586. * @returns the list of angular speed gradients
  57587. */
  57588. GPUParticleSystem.prototype.getVelocityGradients = function () {
  57589. return this._velocityGradients;
  57590. };
  57591. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57592. if (!gradients) {
  57593. return this;
  57594. }
  57595. var index = 0;
  57596. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57597. var valueGradient = gradients_1[_i];
  57598. if (valueGradient.gradient === gradient) {
  57599. gradients.splice(index, 1);
  57600. break;
  57601. }
  57602. index++;
  57603. }
  57604. if (texture) {
  57605. texture.dispose();
  57606. }
  57607. this._releaseBuffers();
  57608. return this;
  57609. };
  57610. /**
  57611. * Adds a new color gradient
  57612. * @param gradient defines the gradient to use (between 0 and 1)
  57613. * @param color defines the color to affect to the specified gradient
  57614. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57615. * @returns the current particle system
  57616. */
  57617. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57618. if (!this._colorGradients) {
  57619. this._colorGradients = [];
  57620. }
  57621. var colorGradient = new BABYLON.ColorGradient();
  57622. colorGradient.gradient = gradient;
  57623. colorGradient.color1 = color1;
  57624. this._colorGradients.push(colorGradient);
  57625. this._colorGradients.sort(function (a, b) {
  57626. if (a.gradient < b.gradient) {
  57627. return -1;
  57628. }
  57629. else if (a.gradient > b.gradient) {
  57630. return 1;
  57631. }
  57632. return 0;
  57633. });
  57634. if (this._colorGradientsTexture) {
  57635. this._colorGradientsTexture.dispose();
  57636. this._colorGradientsTexture = null;
  57637. }
  57638. this._releaseBuffers();
  57639. return this;
  57640. };
  57641. /**
  57642. * Remove a specific color gradient
  57643. * @param gradient defines the gradient to remove
  57644. * @returns the current particle system
  57645. */
  57646. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57647. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57648. this._colorGradientsTexture = null;
  57649. return this;
  57650. };
  57651. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57652. var valueGradient = new BABYLON.FactorGradient();
  57653. valueGradient.gradient = gradient;
  57654. valueGradient.factor1 = factor;
  57655. factorGradients.push(valueGradient);
  57656. factorGradients.sort(function (a, b) {
  57657. if (a.gradient < b.gradient) {
  57658. return -1;
  57659. }
  57660. else if (a.gradient > b.gradient) {
  57661. return 1;
  57662. }
  57663. return 0;
  57664. });
  57665. this._releaseBuffers();
  57666. };
  57667. /**
  57668. * Adds a new size gradient
  57669. * @param gradient defines the gradient to use (between 0 and 1)
  57670. * @param factor defines the size factor to affect to the specified gradient
  57671. * @returns the current particle system
  57672. */
  57673. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57674. if (!this._sizeGradients) {
  57675. this._sizeGradients = [];
  57676. }
  57677. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57678. if (this._sizeGradientsTexture) {
  57679. this._sizeGradientsTexture.dispose();
  57680. this._sizeGradientsTexture = null;
  57681. }
  57682. this._releaseBuffers();
  57683. return this;
  57684. };
  57685. /**
  57686. * Remove a specific size gradient
  57687. * @param gradient defines the gradient to remove
  57688. * @returns the current particle system
  57689. */
  57690. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57691. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57692. this._sizeGradientsTexture = null;
  57693. return this;
  57694. };
  57695. /**
  57696. * Adds a new angular speed gradient
  57697. * @param gradient defines the gradient to use (between 0 and 1)
  57698. * @param factor defines the size factor to affect to the specified gradient
  57699. * @returns the current particle system
  57700. */
  57701. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57702. if (!this._angularSpeedGradients) {
  57703. this._angularSpeedGradients = [];
  57704. }
  57705. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57706. if (this._angularSpeedGradientsTexture) {
  57707. this._angularSpeedGradientsTexture.dispose();
  57708. this._angularSpeedGradientsTexture = null;
  57709. }
  57710. this._releaseBuffers();
  57711. return this;
  57712. };
  57713. /**
  57714. * Remove a specific angular speed gradient
  57715. * @param gradient defines the gradient to remove
  57716. * @returns the current particle system
  57717. */
  57718. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57719. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57720. this._angularSpeedGradientsTexture = null;
  57721. return this;
  57722. };
  57723. /**
  57724. * Adds a new velocity gradient
  57725. * @param gradient defines the gradient to use (between 0 and 1)
  57726. * @param factor defines the size factor to affect to the specified gradient
  57727. * @returns the current particle system
  57728. */
  57729. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  57730. if (!this._velocityGradients) {
  57731. this._velocityGradients = [];
  57732. }
  57733. this._addFactorGradient(this._velocityGradients, gradient, factor);
  57734. if (this._velocityGradientsTexture) {
  57735. this._velocityGradientsTexture.dispose();
  57736. this._velocityGradientsTexture = null;
  57737. }
  57738. this._releaseBuffers();
  57739. return this;
  57740. };
  57741. /**
  57742. * Remove a specific velocity gradient
  57743. * @param gradient defines the gradient to remove
  57744. * @returns the current particle system
  57745. */
  57746. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  57747. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  57748. this._velocityGradientsTexture = null;
  57749. return this;
  57750. };
  57751. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57752. var updateVertexBuffers = {};
  57753. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57754. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57755. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57756. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57757. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57758. var offset = 12;
  57759. if (!this._colorGradientsTexture) {
  57760. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57761. offset += 4;
  57762. }
  57763. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57764. offset += 3;
  57765. if (!this._isBillboardBased) {
  57766. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57767. offset += 3;
  57768. }
  57769. if (this._angularSpeedGradientsTexture) {
  57770. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57771. offset += 1;
  57772. }
  57773. else {
  57774. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57775. offset += 2;
  57776. }
  57777. if (this._isAnimationSheetEnabled) {
  57778. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57779. offset += 1;
  57780. }
  57781. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57782. this._engine.bindArrayBuffer(null);
  57783. return vao;
  57784. };
  57785. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57786. var renderVertexBuffers = {};
  57787. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57788. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57789. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57790. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57791. var offset = 12;
  57792. if (!this._colorGradientsTexture) {
  57793. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57794. offset += 4;
  57795. }
  57796. offset += 3; // Direction
  57797. if (!this._isBillboardBased) {
  57798. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57799. offset += 3;
  57800. }
  57801. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57802. if (this._angularSpeedGradientsTexture) {
  57803. offset++;
  57804. }
  57805. else {
  57806. offset += 2;
  57807. }
  57808. if (this._isAnimationSheetEnabled) {
  57809. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57810. offset += 1;
  57811. }
  57812. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57813. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57814. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57815. this._engine.bindArrayBuffer(null);
  57816. return vao;
  57817. };
  57818. GPUParticleSystem.prototype._initialize = function (force) {
  57819. if (force === void 0) { force = false; }
  57820. if (this._buffer0 && !force) {
  57821. return;
  57822. }
  57823. var engine = this._scene.getEngine();
  57824. var data = new Array();
  57825. if (!this.isBillboardBased) {
  57826. this._attributesStrideSize += 3;
  57827. }
  57828. if (this._colorGradientsTexture) {
  57829. this._attributesStrideSize -= 4;
  57830. }
  57831. if (this._angularSpeedGradientsTexture) {
  57832. this._attributesStrideSize -= 1;
  57833. }
  57834. if (this._isAnimationSheetEnabled) {
  57835. this._attributesStrideSize += 1;
  57836. }
  57837. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57838. // position
  57839. data.push(0.0);
  57840. data.push(0.0);
  57841. data.push(0.0);
  57842. // Age and life
  57843. data.push(0.0); // create the particle as a dead one to create a new one at start
  57844. data.push(0.0);
  57845. // Seed
  57846. data.push(Math.random());
  57847. data.push(Math.random());
  57848. data.push(Math.random());
  57849. data.push(Math.random());
  57850. // Size
  57851. data.push(0.0);
  57852. data.push(0.0);
  57853. data.push(0.0);
  57854. if (!this._colorGradientsTexture) {
  57855. // color
  57856. data.push(0.0);
  57857. data.push(0.0);
  57858. data.push(0.0);
  57859. data.push(0.0);
  57860. }
  57861. // direction
  57862. data.push(0.0);
  57863. data.push(0.0);
  57864. data.push(0.0);
  57865. if (!this.isBillboardBased) {
  57866. // initialDirection
  57867. data.push(0.0);
  57868. data.push(0.0);
  57869. data.push(0.0);
  57870. }
  57871. // angle
  57872. data.push(0.0);
  57873. if (!this._angularSpeedGradientsTexture) {
  57874. data.push(0.0);
  57875. }
  57876. if (this._isAnimationSheetEnabled) {
  57877. data.push(0.0);
  57878. }
  57879. }
  57880. // Sprite data
  57881. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57882. -0.5, 0.5, 0, 1,
  57883. -0.5, -0.5, 0, 0,
  57884. 0.5, -0.5, 1, 0]);
  57885. // Buffers
  57886. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57887. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57888. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57889. // Update VAO
  57890. this._updateVAO = [];
  57891. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57892. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57893. // Render VAO
  57894. this._renderVAO = [];
  57895. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57896. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57897. // Links
  57898. this._sourceBuffer = this._buffer0;
  57899. this._targetBuffer = this._buffer1;
  57900. };
  57901. /** @hidden */
  57902. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57903. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57904. if (this._isBillboardBased) {
  57905. defines += "\n#define BILLBOARD";
  57906. }
  57907. if (this._colorGradientsTexture) {
  57908. defines += "\n#define COLORGRADIENTS";
  57909. }
  57910. if (this._sizeGradientsTexture) {
  57911. defines += "\n#define SIZEGRADIENTS";
  57912. }
  57913. if (this._angularSpeedGradientsTexture) {
  57914. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57915. }
  57916. if (this._velocityGradientsTexture) {
  57917. defines += "\n#define VELOCITYGRADIENTS";
  57918. }
  57919. if (this.isAnimationSheetEnabled) {
  57920. defines += "\n#define ANIMATESHEET";
  57921. }
  57922. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57923. return;
  57924. }
  57925. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57926. if (!this._colorGradientsTexture) {
  57927. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57928. }
  57929. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57930. if (!this._isBillboardBased) {
  57931. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57932. }
  57933. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57934. if (this.isAnimationSheetEnabled) {
  57935. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57936. }
  57937. this._updateEffectOptions.defines = defines;
  57938. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57939. };
  57940. /** @hidden */
  57941. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57942. var defines = "";
  57943. if (this._scene.clipPlane) {
  57944. defines = "\n#define CLIPPLANE";
  57945. }
  57946. if (this._isBillboardBased) {
  57947. defines += "\n#define BILLBOARD";
  57948. switch (this.billboardMode) {
  57949. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57950. defines += "\n#define BILLBOARDY";
  57951. break;
  57952. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57953. default:
  57954. break;
  57955. }
  57956. }
  57957. if (this._colorGradientsTexture) {
  57958. defines += "\n#define COLORGRADIENTS";
  57959. }
  57960. if (this.isAnimationSheetEnabled) {
  57961. defines += "\n#define ANIMATESHEET";
  57962. }
  57963. if (this._renderEffect && this._renderEffect.defines === defines) {
  57964. return;
  57965. }
  57966. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57967. };
  57968. /**
  57969. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57970. * @param preWarm defines if we are in the pre-warmimg phase
  57971. */
  57972. GPUParticleSystem.prototype.animate = function (preWarm) {
  57973. if (preWarm === void 0) { preWarm = false; }
  57974. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57975. this._actualFrame += this._timeDelta;
  57976. if (!this._stopped) {
  57977. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57978. this.stop();
  57979. }
  57980. }
  57981. };
  57982. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57983. var texture = this[textureName];
  57984. if (!factorGradients || !factorGradients.length || texture) {
  57985. return;
  57986. }
  57987. var data = new Float32Array(this._rawTextureWidth);
  57988. for (var x = 0; x < this._rawTextureWidth; x++) {
  57989. var ratio = x / this._rawTextureWidth;
  57990. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57991. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57992. });
  57993. }
  57994. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57995. };
  57996. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57997. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57998. };
  57999. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  58000. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  58001. };
  58002. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  58003. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  58004. };
  58005. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  58006. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  58007. return;
  58008. }
  58009. var data = new Uint8Array(this._rawTextureWidth * 4);
  58010. var tmpColor = BABYLON.Tmp.Color4[0];
  58011. for (var x = 0; x < this._rawTextureWidth; x++) {
  58012. var ratio = x / this._rawTextureWidth;
  58013. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  58014. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  58015. data[x * 4] = tmpColor.r * 255;
  58016. data[x * 4 + 1] = tmpColor.g * 255;
  58017. data[x * 4 + 2] = tmpColor.b * 255;
  58018. data[x * 4 + 3] = tmpColor.a * 255;
  58019. });
  58020. }
  58021. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58022. };
  58023. /**
  58024. * Renders the particle system in its current state
  58025. * @param preWarm defines if the system should only update the particles but not render them
  58026. * @returns the current number of particles
  58027. */
  58028. GPUParticleSystem.prototype.render = function (preWarm) {
  58029. if (preWarm === void 0) { preWarm = false; }
  58030. if (!this._started) {
  58031. return 0;
  58032. }
  58033. this._createColorGradientTexture();
  58034. this._createSizeGradientTexture();
  58035. this._createAngularSpeedGradientTexture();
  58036. this._createVelocityGradientTexture();
  58037. this._recreateUpdateEffect();
  58038. this._recreateRenderEffect();
  58039. if (!this.isReady()) {
  58040. return 0;
  58041. }
  58042. if (!preWarm) {
  58043. if (!this._preWarmDone && this.preWarmCycles) {
  58044. for (var index = 0; index < this.preWarmCycles; index++) {
  58045. this.animate(true);
  58046. this.render(true);
  58047. }
  58048. this._preWarmDone = true;
  58049. }
  58050. if (this._currentRenderId === this._scene.getRenderId()) {
  58051. return 0;
  58052. }
  58053. this._currentRenderId = this._scene.getRenderId();
  58054. }
  58055. // Get everything ready to render
  58056. this._initialize();
  58057. this._accumulatedCount += this.emitRate * this._timeDelta;
  58058. if (this._accumulatedCount > 1) {
  58059. var intPart = this._accumulatedCount | 0;
  58060. this._accumulatedCount -= intPart;
  58061. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  58062. }
  58063. if (!this._currentActiveCount) {
  58064. return 0;
  58065. }
  58066. // Enable update effect
  58067. this._engine.enableEffect(this._updateEffect);
  58068. this._engine.setState(false);
  58069. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  58070. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  58071. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  58072. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  58073. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  58074. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  58075. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  58076. if (!this._colorGradientsTexture) {
  58077. this._updateEffect.setDirectColor4("color1", this.color1);
  58078. this._updateEffect.setDirectColor4("color2", this.color2);
  58079. }
  58080. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  58081. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  58082. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  58083. this._updateEffect.setVector3("gravity", this.gravity);
  58084. if (this._sizeGradientsTexture) {
  58085. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  58086. }
  58087. if (this._angularSpeedGradientsTexture) {
  58088. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  58089. }
  58090. if (this._velocityGradientsTexture) {
  58091. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  58092. }
  58093. if (this.particleEmitterType) {
  58094. this.particleEmitterType.applyToShader(this._updateEffect);
  58095. }
  58096. if (this._isAnimationSheetEnabled) {
  58097. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  58098. }
  58099. var emitterWM;
  58100. if (this.emitter.position) {
  58101. var emitterMesh = this.emitter;
  58102. emitterWM = emitterMesh.getWorldMatrix();
  58103. }
  58104. else {
  58105. var emitterPosition = this.emitter;
  58106. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  58107. }
  58108. this._updateEffect.setMatrix("emitterWM", emitterWM);
  58109. // Bind source VAO
  58110. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  58111. // Update
  58112. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  58113. this._engine.setRasterizerState(false);
  58114. this._engine.beginTransformFeedback();
  58115. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  58116. this._engine.endTransformFeedback();
  58117. this._engine.setRasterizerState(true);
  58118. this._engine.bindTransformFeedbackBuffer(null);
  58119. if (!preWarm) {
  58120. // Enable render effect
  58121. this._engine.enableEffect(this._renderEffect);
  58122. var viewMatrix = this._scene.getViewMatrix();
  58123. this._renderEffect.setMatrix("view", viewMatrix);
  58124. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  58125. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  58126. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  58127. if (this._colorGradientsTexture) {
  58128. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  58129. }
  58130. else {
  58131. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  58132. }
  58133. if (this._isAnimationSheetEnabled && this.particleTexture) {
  58134. var baseSize = this.particleTexture.getBaseSize();
  58135. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  58136. }
  58137. if (this._isBillboardBased) {
  58138. var camera = this._scene.activeCamera;
  58139. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  58140. }
  58141. if (this._scene.clipPlane) {
  58142. var clipPlane = this._scene.clipPlane;
  58143. var invView = viewMatrix.clone();
  58144. invView.invert();
  58145. this._renderEffect.setMatrix("invView", invView);
  58146. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  58147. }
  58148. // Draw order
  58149. switch (this.blendMode) {
  58150. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  58151. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  58152. break;
  58153. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  58154. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  58155. break;
  58156. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  58157. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  58158. break;
  58159. }
  58160. if (this.forceDepthWrite) {
  58161. this._engine.setDepthWrite(true);
  58162. }
  58163. // Bind source VAO
  58164. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58165. // Render
  58166. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58167. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58168. }
  58169. // Switch VAOs
  58170. this._targetIndex++;
  58171. if (this._targetIndex === 2) {
  58172. this._targetIndex = 0;
  58173. }
  58174. // Switch buffers
  58175. var tmpBuffer = this._sourceBuffer;
  58176. this._sourceBuffer = this._targetBuffer;
  58177. this._targetBuffer = tmpBuffer;
  58178. return this._currentActiveCount;
  58179. };
  58180. /**
  58181. * Rebuilds the particle system
  58182. */
  58183. GPUParticleSystem.prototype.rebuild = function () {
  58184. this._initialize(true);
  58185. };
  58186. GPUParticleSystem.prototype._releaseBuffers = function () {
  58187. if (this._buffer0) {
  58188. this._buffer0.dispose();
  58189. this._buffer0 = null;
  58190. }
  58191. if (this._buffer1) {
  58192. this._buffer1.dispose();
  58193. this._buffer1 = null;
  58194. }
  58195. if (this._spriteBuffer) {
  58196. this._spriteBuffer.dispose();
  58197. this._spriteBuffer = null;
  58198. }
  58199. };
  58200. GPUParticleSystem.prototype._releaseVAOs = function () {
  58201. if (!this._updateVAO) {
  58202. return;
  58203. }
  58204. for (var index = 0; index < this._updateVAO.length; index++) {
  58205. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58206. }
  58207. this._updateVAO = [];
  58208. for (var index = 0; index < this._renderVAO.length; index++) {
  58209. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58210. }
  58211. this._renderVAO = [];
  58212. };
  58213. /**
  58214. * Disposes the particle system and free the associated resources
  58215. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58216. */
  58217. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58218. if (disposeTexture === void 0) { disposeTexture = true; }
  58219. var index = this._scene.particleSystems.indexOf(this);
  58220. if (index > -1) {
  58221. this._scene.particleSystems.splice(index, 1);
  58222. }
  58223. this._releaseBuffers();
  58224. this._releaseVAOs();
  58225. if (this._colorGradientsTexture) {
  58226. this._colorGradientsTexture.dispose();
  58227. this._colorGradientsTexture = null;
  58228. }
  58229. if (this._sizeGradientsTexture) {
  58230. this._sizeGradientsTexture.dispose();
  58231. this._sizeGradientsTexture = null;
  58232. }
  58233. if (this._angularSpeedGradientsTexture) {
  58234. this._angularSpeedGradientsTexture.dispose();
  58235. this._angularSpeedGradientsTexture = null;
  58236. }
  58237. if (this._velocityGradientsTexture) {
  58238. this._velocityGradientsTexture.dispose();
  58239. this._velocityGradientsTexture = null;
  58240. }
  58241. if (this._randomTexture) {
  58242. this._randomTexture.dispose();
  58243. this._randomTexture = null;
  58244. }
  58245. if (this._randomTexture2) {
  58246. this._randomTexture2.dispose();
  58247. this._randomTexture2 = null;
  58248. }
  58249. if (disposeTexture && this.particleTexture) {
  58250. this.particleTexture.dispose();
  58251. this.particleTexture = null;
  58252. }
  58253. // Callback
  58254. this.onDisposeObservable.notifyObservers(this);
  58255. this.onDisposeObservable.clear();
  58256. };
  58257. /**
  58258. * Clones the particle system.
  58259. * @param name The name of the cloned object
  58260. * @param newEmitter The new emitter to use
  58261. * @returns the cloned particle system
  58262. */
  58263. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58264. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58265. BABYLON.Tools.DeepCopy(this, result);
  58266. if (newEmitter === undefined) {
  58267. newEmitter = this.emitter;
  58268. }
  58269. result.emitter = newEmitter;
  58270. if (this.particleTexture) {
  58271. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58272. }
  58273. return result;
  58274. };
  58275. /**
  58276. * Serializes the particle system to a JSON object.
  58277. * @returns the JSON object
  58278. */
  58279. GPUParticleSystem.prototype.serialize = function () {
  58280. var serializationObject = {};
  58281. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58282. serializationObject.activeParticleCount = this.activeParticleCount;
  58283. return serializationObject;
  58284. };
  58285. /**
  58286. * Parses a JSON object to create a GPU particle system.
  58287. * @param parsedParticleSystem The JSON object to parse
  58288. * @param scene The scene to create the particle system in
  58289. * @param rootUrl The root url to use to load external dependencies like texture
  58290. * @returns the parsed GPU particle system
  58291. */
  58292. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58293. var name = parsedParticleSystem.name;
  58294. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58295. if (parsedParticleSystem.activeParticleCount) {
  58296. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58297. }
  58298. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58299. return particleSystem;
  58300. };
  58301. return GPUParticleSystem;
  58302. }());
  58303. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58304. })(BABYLON || (BABYLON = {}));
  58305. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58306. var BABYLON;
  58307. (function (BABYLON) {
  58308. /**
  58309. * Represents one particle of a solid particle system.
  58310. */
  58311. var SolidParticle = /** @class */ (function () {
  58312. /**
  58313. * Creates a Solid Particle object.
  58314. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58315. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58316. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58317. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58318. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58319. * @param shapeId (integer) is the model shape identifier in the SPS.
  58320. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58321. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58322. */
  58323. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58324. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58325. /**
  58326. * particle global index
  58327. */
  58328. this.idx = 0;
  58329. /**
  58330. * The color of the particle
  58331. */
  58332. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58333. /**
  58334. * The world space position of the particle.
  58335. */
  58336. this.position = BABYLON.Vector3.Zero();
  58337. /**
  58338. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58339. */
  58340. this.rotation = BABYLON.Vector3.Zero();
  58341. /**
  58342. * The scaling of the particle.
  58343. */
  58344. this.scaling = BABYLON.Vector3.One();
  58345. /**
  58346. * The uvs of the particle.
  58347. */
  58348. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58349. /**
  58350. * The current speed of the particle.
  58351. */
  58352. this.velocity = BABYLON.Vector3.Zero();
  58353. /**
  58354. * The pivot point in the particle local space.
  58355. */
  58356. this.pivot = BABYLON.Vector3.Zero();
  58357. /**
  58358. * Must the particle be translated from its pivot point in its local space ?
  58359. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58360. * Default : false
  58361. */
  58362. this.translateFromPivot = false;
  58363. /**
  58364. * Is the particle active or not ?
  58365. */
  58366. this.alive = true;
  58367. /**
  58368. * Is the particle visible or not ?
  58369. */
  58370. this.isVisible = true;
  58371. /**
  58372. * Index of this particle in the global "positions" array (Internal use)
  58373. */
  58374. this._pos = 0;
  58375. /**
  58376. * Index of this particle in the global "indices" array (Internal use)
  58377. */
  58378. this._ind = 0;
  58379. /**
  58380. * ModelShape id of this particle
  58381. */
  58382. this.shapeId = 0;
  58383. /**
  58384. * Index of the particle in its shape id (Internal use)
  58385. */
  58386. this.idxInShape = 0;
  58387. /**
  58388. * Still set as invisible in order to skip useless computations (Internal use)
  58389. */
  58390. this._stillInvisible = false;
  58391. /**
  58392. * Last computed particle rotation matrix
  58393. */
  58394. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58395. /**
  58396. * Parent particle Id, if any.
  58397. * Default null.
  58398. */
  58399. this.parentId = null;
  58400. /**
  58401. * Internal global position in the SPS.
  58402. */
  58403. this._globalPosition = BABYLON.Vector3.Zero();
  58404. this.idx = particleIndex;
  58405. this._pos = positionIndex;
  58406. this._ind = indiceIndex;
  58407. this._model = model;
  58408. this.shapeId = shapeId;
  58409. this.idxInShape = idxInShape;
  58410. this._sps = sps;
  58411. if (modelBoundingInfo) {
  58412. this._modelBoundingInfo = modelBoundingInfo;
  58413. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58414. }
  58415. }
  58416. Object.defineProperty(SolidParticle.prototype, "scale", {
  58417. /**
  58418. * Legacy support, changed scale to scaling
  58419. */
  58420. get: function () {
  58421. return this.scaling;
  58422. },
  58423. /**
  58424. * Legacy support, changed scale to scaling
  58425. */
  58426. set: function (scale) {
  58427. this.scaling = scale;
  58428. },
  58429. enumerable: true,
  58430. configurable: true
  58431. });
  58432. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58433. /**
  58434. * Legacy support, changed quaternion to rotationQuaternion
  58435. */
  58436. get: function () {
  58437. return this.rotationQuaternion;
  58438. },
  58439. /**
  58440. * Legacy support, changed quaternion to rotationQuaternion
  58441. */
  58442. set: function (q) {
  58443. this.rotationQuaternion = q;
  58444. },
  58445. enumerable: true,
  58446. configurable: true
  58447. });
  58448. /**
  58449. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58450. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58451. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58452. * @returns true if it intersects
  58453. */
  58454. SolidParticle.prototype.intersectsMesh = function (target) {
  58455. if (!this._boundingInfo || !target._boundingInfo) {
  58456. return false;
  58457. }
  58458. if (this._sps._bSphereOnly) {
  58459. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58460. }
  58461. return this._boundingInfo.intersects(target._boundingInfo, false);
  58462. };
  58463. return SolidParticle;
  58464. }());
  58465. BABYLON.SolidParticle = SolidParticle;
  58466. /**
  58467. * Represents the shape of the model used by one particle of a solid particle system.
  58468. * SPS internal tool, don't use it manually.
  58469. */
  58470. var ModelShape = /** @class */ (function () {
  58471. /**
  58472. * 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.
  58473. * SPS internal tool, don't use it manually.
  58474. * @hidden
  58475. */
  58476. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58477. /**
  58478. * length of the shape in the model indices array (internal use)
  58479. */
  58480. this._indicesLength = 0;
  58481. this.shapeID = id;
  58482. this._shape = shape;
  58483. this._indicesLength = indicesLength;
  58484. this._shapeUV = shapeUV;
  58485. this._positionFunction = posFunction;
  58486. this._vertexFunction = vtxFunction;
  58487. }
  58488. return ModelShape;
  58489. }());
  58490. BABYLON.ModelShape = ModelShape;
  58491. /**
  58492. * Represents a Depth Sorted Particle in the solid particle system.
  58493. */
  58494. var DepthSortedParticle = /** @class */ (function () {
  58495. function DepthSortedParticle() {
  58496. /**
  58497. * Index of the particle in the "indices" array
  58498. */
  58499. this.ind = 0;
  58500. /**
  58501. * Length of the particle shape in the "indices" array
  58502. */
  58503. this.indicesLength = 0;
  58504. /**
  58505. * Squared distance from the particle to the camera
  58506. */
  58507. this.sqDistance = 0.0;
  58508. }
  58509. return DepthSortedParticle;
  58510. }());
  58511. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58512. })(BABYLON || (BABYLON = {}));
  58513. //# sourceMappingURL=babylon.solidParticle.js.map
  58514. var BABYLON;
  58515. (function (BABYLON) {
  58516. /**
  58517. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58518. *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.
  58519. * The SPS is also a particle system. It provides some methods to manage the particles.
  58520. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58521. *
  58522. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58523. */
  58524. var SolidParticleSystem = /** @class */ (function () {
  58525. /**
  58526. * Creates a SPS (Solid Particle System) object.
  58527. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58528. * @param scene (Scene) is the scene in which the SPS is added.
  58529. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58530. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58531. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58532. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58533. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58534. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58535. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58536. */
  58537. function SolidParticleSystem(name, scene, options) {
  58538. /**
  58539. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58540. * Example : var p = SPS.particles[i];
  58541. */
  58542. this.particles = new Array();
  58543. /**
  58544. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58545. */
  58546. this.nbParticles = 0;
  58547. /**
  58548. * If the particles must ever face the camera (default false). Useful for planar particles.
  58549. */
  58550. this.billboard = false;
  58551. /**
  58552. * Recompute normals when adding a shape
  58553. */
  58554. this.recomputeNormals = true;
  58555. /**
  58556. * This a counter ofr your own usage. It's not set by any SPS functions.
  58557. */
  58558. this.counter = 0;
  58559. /**
  58560. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58561. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58562. */
  58563. this.vars = {};
  58564. /**
  58565. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58566. */
  58567. this._bSphereOnly = false;
  58568. /**
  58569. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58570. */
  58571. this._bSphereRadiusFactor = 1.0;
  58572. this._positions = new Array();
  58573. this._indices = new Array();
  58574. this._normals = new Array();
  58575. this._colors = new Array();
  58576. this._uvs = new Array();
  58577. this._index = 0; // indices index
  58578. this._updatable = true;
  58579. this._pickable = false;
  58580. this._isVisibilityBoxLocked = false;
  58581. this._alwaysVisible = false;
  58582. this._depthSort = false;
  58583. this._shapeCounter = 0;
  58584. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58585. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58586. this._computeParticleColor = true;
  58587. this._computeParticleTexture = true;
  58588. this._computeParticleRotation = true;
  58589. this._computeParticleVertex = false;
  58590. this._computeBoundingBox = false;
  58591. this._depthSortParticles = true;
  58592. this._cam_axisZ = BABYLON.Vector3.Zero();
  58593. this._cam_axisY = BABYLON.Vector3.Zero();
  58594. this._cam_axisX = BABYLON.Vector3.Zero();
  58595. this._axisZ = BABYLON.Axis.Z;
  58596. this._camDir = BABYLON.Vector3.Zero();
  58597. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58598. this._rotMatrix = new BABYLON.Matrix();
  58599. this._invertMatrix = new BABYLON.Matrix();
  58600. this._rotated = BABYLON.Vector3.Zero();
  58601. this._quaternion = new BABYLON.Quaternion();
  58602. this._vertex = BABYLON.Vector3.Zero();
  58603. this._normal = BABYLON.Vector3.Zero();
  58604. this._yaw = 0.0;
  58605. this._pitch = 0.0;
  58606. this._roll = 0.0;
  58607. this._halfroll = 0.0;
  58608. this._halfpitch = 0.0;
  58609. this._halfyaw = 0.0;
  58610. this._sinRoll = 0.0;
  58611. this._cosRoll = 0.0;
  58612. this._sinPitch = 0.0;
  58613. this._cosPitch = 0.0;
  58614. this._sinYaw = 0.0;
  58615. this._cosYaw = 0.0;
  58616. this._mustUnrotateFixedNormals = false;
  58617. this._minimum = BABYLON.Vector3.Zero();
  58618. this._maximum = BABYLON.Vector3.Zero();
  58619. this._minBbox = BABYLON.Vector3.Zero();
  58620. this._maxBbox = BABYLON.Vector3.Zero();
  58621. this._particlesIntersect = false;
  58622. this._depthSortFunction = function (p1, p2) {
  58623. return (p2.sqDistance - p1.sqDistance);
  58624. };
  58625. this._needs32Bits = false;
  58626. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58627. this._scaledPivot = BABYLON.Vector3.Zero();
  58628. this._particleHasParent = false;
  58629. this.name = name;
  58630. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58631. this._camera = scene.activeCamera;
  58632. this._pickable = options ? options.isPickable : false;
  58633. this._depthSort = options ? options.enableDepthSort : false;
  58634. this._particlesIntersect = options ? options.particleIntersection : false;
  58635. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58636. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58637. if (options && options.updatable !== undefined) {
  58638. this._updatable = options.updatable;
  58639. }
  58640. else {
  58641. this._updatable = true;
  58642. }
  58643. if (this._pickable) {
  58644. this.pickedParticles = [];
  58645. }
  58646. if (this._depthSort) {
  58647. this.depthSortedParticles = [];
  58648. }
  58649. }
  58650. /**
  58651. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58652. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58653. * @returns the created mesh
  58654. */
  58655. SolidParticleSystem.prototype.buildMesh = function () {
  58656. if (this.nbParticles === 0) {
  58657. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58658. this.addShape(triangle, 1);
  58659. triangle.dispose();
  58660. }
  58661. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58662. this._positions32 = new Float32Array(this._positions);
  58663. this._uvs32 = new Float32Array(this._uvs);
  58664. this._colors32 = new Float32Array(this._colors);
  58665. if (this.recomputeNormals) {
  58666. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58667. }
  58668. this._normals32 = new Float32Array(this._normals);
  58669. this._fixedNormal32 = new Float32Array(this._normals);
  58670. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58671. this._unrotateFixedNormals();
  58672. }
  58673. var vertexData = new BABYLON.VertexData();
  58674. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58675. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58676. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58677. if (this._uvs32.length > 0) {
  58678. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58679. }
  58680. if (this._colors32.length > 0) {
  58681. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58682. }
  58683. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58684. vertexData.applyToMesh(mesh, this._updatable);
  58685. this.mesh = mesh;
  58686. this.mesh.isPickable = this._pickable;
  58687. // free memory
  58688. if (!this._depthSort) {
  58689. this._indices = null;
  58690. }
  58691. this._positions = null;
  58692. this._normals = null;
  58693. this._uvs = null;
  58694. this._colors = null;
  58695. if (!this._updatable) {
  58696. this.particles.length = 0;
  58697. }
  58698. return mesh;
  58699. };
  58700. /**
  58701. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58702. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58703. * Thus the particles generated from `digest()` have their property `position` set yet.
  58704. * @param mesh ( Mesh ) is the mesh to be digested
  58705. * @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
  58706. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58707. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58708. * @returns the current SPS
  58709. */
  58710. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58711. var size = (options && options.facetNb) || 1;
  58712. var number = (options && options.number) || 0;
  58713. var delta = (options && options.delta) || 0;
  58714. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58715. var meshInd = mesh.getIndices();
  58716. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58717. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58718. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58719. var f = 0; // facet counter
  58720. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58721. // compute size from number
  58722. if (number) {
  58723. number = (number > totalFacets) ? totalFacets : number;
  58724. size = Math.round(totalFacets / number);
  58725. delta = 0;
  58726. }
  58727. else {
  58728. size = (size > totalFacets) ? totalFacets : size;
  58729. }
  58730. var facetPos = []; // submesh positions
  58731. var facetInd = []; // submesh indices
  58732. var facetUV = []; // submesh UV
  58733. var facetCol = []; // submesh colors
  58734. var barycenter = BABYLON.Vector3.Zero();
  58735. var sizeO = size;
  58736. while (f < totalFacets) {
  58737. size = sizeO + Math.floor((1 + delta) * Math.random());
  58738. if (f > totalFacets - size) {
  58739. size = totalFacets - f;
  58740. }
  58741. // reset temp arrays
  58742. facetPos.length = 0;
  58743. facetInd.length = 0;
  58744. facetUV.length = 0;
  58745. facetCol.length = 0;
  58746. // iterate over "size" facets
  58747. var fi = 0;
  58748. for (var j = f * 3; j < (f + size) * 3; j++) {
  58749. facetInd.push(fi);
  58750. var i = meshInd[j];
  58751. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58752. if (meshUV) {
  58753. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58754. }
  58755. if (meshCol) {
  58756. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58757. }
  58758. fi++;
  58759. }
  58760. // create a model shape for each single particle
  58761. var idx = this.nbParticles;
  58762. var shape = this._posToShape(facetPos);
  58763. var shapeUV = this._uvsToShapeUV(facetUV);
  58764. // compute the barycenter of the shape
  58765. var v;
  58766. for (v = 0; v < shape.length; v++) {
  58767. barycenter.addInPlace(shape[v]);
  58768. }
  58769. barycenter.scaleInPlace(1 / shape.length);
  58770. // shift the shape from its barycenter to the origin
  58771. for (v = 0; v < shape.length; v++) {
  58772. shape[v].subtractInPlace(barycenter);
  58773. }
  58774. var bInfo;
  58775. if (this._particlesIntersect) {
  58776. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58777. }
  58778. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58779. // add the particle in the SPS
  58780. var currentPos = this._positions.length;
  58781. var currentInd = this._indices.length;
  58782. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58783. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58784. // initialize the particle position
  58785. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58786. this._index += shape.length;
  58787. idx++;
  58788. this.nbParticles++;
  58789. this._shapeCounter++;
  58790. f += size;
  58791. }
  58792. return this;
  58793. };
  58794. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58795. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58796. var index = 0;
  58797. var idx = 0;
  58798. for (var p = 0; p < this.particles.length; p++) {
  58799. this._particle = this.particles[p];
  58800. this._shape = this._particle._model._shape;
  58801. if (this._particle.rotationQuaternion) {
  58802. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58803. }
  58804. else {
  58805. this._yaw = this._particle.rotation.y;
  58806. this._pitch = this._particle.rotation.x;
  58807. this._roll = this._particle.rotation.z;
  58808. this._quaternionRotationYPR();
  58809. }
  58810. this._quaternionToRotationMatrix();
  58811. this._rotMatrix.invertToRef(this._invertMatrix);
  58812. for (var pt = 0; pt < this._shape.length; pt++) {
  58813. idx = index + pt * 3;
  58814. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58815. this._fixedNormal32[idx] = this._normal.x;
  58816. this._fixedNormal32[idx + 1] = this._normal.y;
  58817. this._fixedNormal32[idx + 2] = this._normal.z;
  58818. }
  58819. index = idx + 3;
  58820. }
  58821. };
  58822. //reset copy
  58823. SolidParticleSystem.prototype._resetCopy = function () {
  58824. this._copy.position.x = 0;
  58825. this._copy.position.y = 0;
  58826. this._copy.position.z = 0;
  58827. this._copy.rotation.x = 0;
  58828. this._copy.rotation.y = 0;
  58829. this._copy.rotation.z = 0;
  58830. this._copy.rotationQuaternion = null;
  58831. this._copy.scaling.x = 1.0;
  58832. this._copy.scaling.y = 1.0;
  58833. this._copy.scaling.z = 1.0;
  58834. this._copy.uvs.x = 0;
  58835. this._copy.uvs.y = 0;
  58836. this._copy.uvs.z = 1.0;
  58837. this._copy.uvs.w = 1.0;
  58838. this._copy.color = null;
  58839. this._copy.translateFromPivot = false;
  58840. };
  58841. // _meshBuilder : inserts the shape model in the global SPS mesh
  58842. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58843. var i;
  58844. var u = 0;
  58845. var c = 0;
  58846. var n = 0;
  58847. this._resetCopy();
  58848. if (options && options.positionFunction) { // call to custom positionFunction
  58849. options.positionFunction(this._copy, idx, idxInShape);
  58850. this._mustUnrotateFixedNormals = true;
  58851. }
  58852. if (this._copy.rotationQuaternion) {
  58853. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58854. }
  58855. else {
  58856. this._yaw = this._copy.rotation.y;
  58857. this._pitch = this._copy.rotation.x;
  58858. this._roll = this._copy.rotation.z;
  58859. this._quaternionRotationYPR();
  58860. }
  58861. this._quaternionToRotationMatrix();
  58862. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58863. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58864. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58865. if (this._copy.translateFromPivot) {
  58866. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58867. }
  58868. else {
  58869. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58870. }
  58871. for (i = 0; i < shape.length; i++) {
  58872. this._vertex.x = shape[i].x;
  58873. this._vertex.y = shape[i].y;
  58874. this._vertex.z = shape[i].z;
  58875. if (options && options.vertexFunction) {
  58876. options.vertexFunction(this._copy, this._vertex, i);
  58877. }
  58878. this._vertex.x *= this._copy.scaling.x;
  58879. this._vertex.y *= this._copy.scaling.y;
  58880. this._vertex.z *= this._copy.scaling.z;
  58881. this._vertex.x -= this._scaledPivot.x;
  58882. this._vertex.y -= this._scaledPivot.y;
  58883. this._vertex.z -= this._scaledPivot.z;
  58884. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58885. this._rotated.addInPlace(this._pivotBackTranslation);
  58886. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58887. if (meshUV) {
  58888. 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);
  58889. u += 2;
  58890. }
  58891. if (this._copy.color) {
  58892. this._color = this._copy.color;
  58893. }
  58894. else if (meshCol && meshCol[c] !== undefined) {
  58895. this._color.r = meshCol[c];
  58896. this._color.g = meshCol[c + 1];
  58897. this._color.b = meshCol[c + 2];
  58898. this._color.a = meshCol[c + 3];
  58899. }
  58900. else {
  58901. this._color.r = 1.0;
  58902. this._color.g = 1.0;
  58903. this._color.b = 1.0;
  58904. this._color.a = 1.0;
  58905. }
  58906. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58907. c += 4;
  58908. if (!this.recomputeNormals && meshNor) {
  58909. this._normal.x = meshNor[n];
  58910. this._normal.y = meshNor[n + 1];
  58911. this._normal.z = meshNor[n + 2];
  58912. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58913. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58914. n += 3;
  58915. }
  58916. }
  58917. for (i = 0; i < meshInd.length; i++) {
  58918. var current_ind = p + meshInd[i];
  58919. indices.push(current_ind);
  58920. if (current_ind > 65535) {
  58921. this._needs32Bits = true;
  58922. }
  58923. }
  58924. if (this._pickable) {
  58925. var nbfaces = meshInd.length / 3;
  58926. for (i = 0; i < nbfaces; i++) {
  58927. this.pickedParticles.push({ idx: idx, faceId: i });
  58928. }
  58929. }
  58930. if (this._depthSort) {
  58931. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58932. }
  58933. return this._copy;
  58934. };
  58935. // returns a shape array from positions array
  58936. SolidParticleSystem.prototype._posToShape = function (positions) {
  58937. var shape = [];
  58938. for (var i = 0; i < positions.length; i += 3) {
  58939. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58940. }
  58941. return shape;
  58942. };
  58943. // returns a shapeUV array from a Vector4 uvs
  58944. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58945. var shapeUV = [];
  58946. if (uvs) {
  58947. for (var i = 0; i < uvs.length; i++)
  58948. shapeUV.push(uvs[i]);
  58949. }
  58950. return shapeUV;
  58951. };
  58952. // adds a new particle object in the particles array
  58953. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58954. if (bInfo === void 0) { bInfo = null; }
  58955. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58956. this.particles.push(sp);
  58957. return sp;
  58958. };
  58959. /**
  58960. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58961. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58962. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58963. * @param nb (positive integer) the number of particles to be created from this model
  58964. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58965. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58966. * @returns the number of shapes in the system
  58967. */
  58968. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58969. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58970. var meshInd = mesh.getIndices();
  58971. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58972. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58973. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58974. var bbInfo;
  58975. if (this._particlesIntersect) {
  58976. bbInfo = mesh.getBoundingInfo();
  58977. }
  58978. var shape = this._posToShape(meshPos);
  58979. var shapeUV = this._uvsToShapeUV(meshUV);
  58980. var posfunc = options ? options.positionFunction : null;
  58981. var vtxfunc = options ? options.vertexFunction : null;
  58982. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58983. // particles
  58984. var sp;
  58985. var currentCopy;
  58986. var idx = this.nbParticles;
  58987. for (var i = 0; i < nb; i++) {
  58988. var currentPos = this._positions.length;
  58989. var currentInd = this._indices.length;
  58990. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58991. if (this._updatable) {
  58992. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58993. sp.position.copyFrom(currentCopy.position);
  58994. sp.rotation.copyFrom(currentCopy.rotation);
  58995. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58996. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58997. }
  58998. if (currentCopy.color && sp.color) {
  58999. sp.color.copyFrom(currentCopy.color);
  59000. }
  59001. sp.scaling.copyFrom(currentCopy.scaling);
  59002. sp.uvs.copyFrom(currentCopy.uvs);
  59003. }
  59004. this._index += shape.length;
  59005. idx++;
  59006. }
  59007. this.nbParticles += nb;
  59008. this._shapeCounter++;
  59009. return this._shapeCounter - 1;
  59010. };
  59011. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  59012. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  59013. this._resetCopy();
  59014. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  59015. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  59016. }
  59017. if (this._copy.rotationQuaternion) {
  59018. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  59019. }
  59020. else {
  59021. this._yaw = this._copy.rotation.y;
  59022. this._pitch = this._copy.rotation.x;
  59023. this._roll = this._copy.rotation.z;
  59024. this._quaternionRotationYPR();
  59025. }
  59026. this._quaternionToRotationMatrix();
  59027. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59028. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59029. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59030. if (this._copy.translateFromPivot) {
  59031. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  59032. }
  59033. else {
  59034. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  59035. }
  59036. this._shape = particle._model._shape;
  59037. for (var pt = 0; pt < this._shape.length; pt++) {
  59038. this._vertex.x = this._shape[pt].x;
  59039. this._vertex.y = this._shape[pt].y;
  59040. this._vertex.z = this._shape[pt].z;
  59041. if (particle._model._vertexFunction) {
  59042. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  59043. }
  59044. this._vertex.x *= this._copy.scaling.x;
  59045. this._vertex.y *= this._copy.scaling.y;
  59046. this._vertex.z *= this._copy.scaling.z;
  59047. this._vertex.x -= this._scaledPivot.x;
  59048. this._vertex.y -= this._scaledPivot.y;
  59049. this._vertex.z -= this._scaledPivot.z;
  59050. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  59051. this._rotated.addInPlace(this._pivotBackTranslation);
  59052. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  59053. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  59054. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  59055. }
  59056. particle.position.x = 0.0;
  59057. particle.position.y = 0.0;
  59058. particle.position.z = 0.0;
  59059. particle.rotation.x = 0.0;
  59060. particle.rotation.y = 0.0;
  59061. particle.rotation.z = 0.0;
  59062. particle.rotationQuaternion = null;
  59063. particle.scaling.x = 1.0;
  59064. particle.scaling.y = 1.0;
  59065. particle.scaling.z = 1.0;
  59066. particle.uvs.x = 0.0;
  59067. particle.uvs.y = 0.0;
  59068. particle.uvs.z = 1.0;
  59069. particle.uvs.w = 1.0;
  59070. particle.pivot.x = 0.0;
  59071. particle.pivot.y = 0.0;
  59072. particle.pivot.z = 0.0;
  59073. particle.translateFromPivot = false;
  59074. particle.parentId = null;
  59075. };
  59076. /**
  59077. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  59078. * @returns the SPS.
  59079. */
  59080. SolidParticleSystem.prototype.rebuildMesh = function () {
  59081. for (var p = 0; p < this.particles.length; p++) {
  59082. this._rebuildParticle(this.particles[p]);
  59083. }
  59084. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59085. return this;
  59086. };
  59087. /**
  59088. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  59089. * This method calls `updateParticle()` for each particle of the SPS.
  59090. * For an animated SPS, it is usually called within the render loop.
  59091. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  59092. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  59093. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  59094. * @returns the SPS.
  59095. */
  59096. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  59097. if (start === void 0) { start = 0; }
  59098. if (end === void 0) { end = this.nbParticles - 1; }
  59099. if (update === void 0) { update = true; }
  59100. if (!this._updatable) {
  59101. return this;
  59102. }
  59103. // custom beforeUpdate
  59104. this.beforeUpdateParticles(start, end, update);
  59105. this._cam_axisX.x = 1.0;
  59106. this._cam_axisX.y = 0.0;
  59107. this._cam_axisX.z = 0.0;
  59108. this._cam_axisY.x = 0.0;
  59109. this._cam_axisY.y = 1.0;
  59110. this._cam_axisY.z = 0.0;
  59111. this._cam_axisZ.x = 0.0;
  59112. this._cam_axisZ.y = 0.0;
  59113. this._cam_axisZ.z = 1.0;
  59114. // cases when the World Matrix is to be computed first
  59115. if (this.billboard || this._depthSort) {
  59116. this.mesh.computeWorldMatrix(true);
  59117. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  59118. }
  59119. // if the particles will always face the camera
  59120. if (this.billboard) {
  59121. // compute the camera position and un-rotate it by the current mesh rotation
  59122. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  59123. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  59124. this._cam_axisZ.normalize();
  59125. // same for camera up vector extracted from the cam view matrix
  59126. var view = this._camera.getViewMatrix(true);
  59127. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  59128. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  59129. this._cam_axisY.normalize();
  59130. this._cam_axisX.normalize();
  59131. }
  59132. // if depthSort, compute the camera global position in the mesh local system
  59133. if (this._depthSort) {
  59134. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  59135. }
  59136. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  59137. var idx = 0; // current position index in the global array positions32
  59138. var index = 0; // position start index in the global array positions32 of the current particle
  59139. var colidx = 0; // current color index in the global array colors32
  59140. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  59141. var uvidx = 0; // current uv index in the global array uvs32
  59142. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  59143. var pt = 0; // current index in the particle model shape
  59144. if (this.mesh.isFacetDataEnabled) {
  59145. this._computeBoundingBox = true;
  59146. }
  59147. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  59148. if (this._computeBoundingBox) {
  59149. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  59150. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  59151. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  59152. }
  59153. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  59154. if (this.mesh._boundingInfo) {
  59155. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  59156. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  59157. }
  59158. }
  59159. }
  59160. // particle loop
  59161. index = this.particles[start]._pos;
  59162. var vpos = (index / 3) | 0;
  59163. colorIndex = vpos * 4;
  59164. uvIndex = vpos * 2;
  59165. for (var p = start; p <= end; p++) {
  59166. this._particle = this.particles[p];
  59167. this._shape = this._particle._model._shape;
  59168. this._shapeUV = this._particle._model._shapeUV;
  59169. // call to custom user function to update the particle properties
  59170. this.updateParticle(this._particle);
  59171. // camera-particle distance for depth sorting
  59172. if (this._depthSort && this._depthSortParticles) {
  59173. var dsp = this.depthSortedParticles[p];
  59174. dsp.ind = this._particle._ind;
  59175. dsp.indicesLength = this._particle._model._indicesLength;
  59176. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59177. }
  59178. // skip the computations for inactive or already invisible particles
  59179. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59180. // increment indexes for the next particle
  59181. pt = this._shape.length;
  59182. index += pt * 3;
  59183. colorIndex += pt * 4;
  59184. uvIndex += pt * 2;
  59185. continue;
  59186. }
  59187. if (this._particle.isVisible) {
  59188. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59189. this._particleHasParent = (this._particle.parentId !== null);
  59190. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59191. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59192. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59193. // particle rotation matrix
  59194. if (this.billboard) {
  59195. this._particle.rotation.x = 0.0;
  59196. this._particle.rotation.y = 0.0;
  59197. }
  59198. if (this._computeParticleRotation || this.billboard) {
  59199. if (this._particle.rotationQuaternion) {
  59200. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59201. }
  59202. else {
  59203. this._yaw = this._particle.rotation.y;
  59204. this._pitch = this._particle.rotation.x;
  59205. this._roll = this._particle.rotation.z;
  59206. this._quaternionRotationYPR();
  59207. }
  59208. this._quaternionToRotationMatrix();
  59209. }
  59210. if (this._particleHasParent) {
  59211. this._parent = this.particles[this._particle.parentId];
  59212. 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];
  59213. 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];
  59214. 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];
  59215. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59216. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59217. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59218. if (this._computeParticleRotation || this.billboard) {
  59219. 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];
  59220. 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];
  59221. 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];
  59222. 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];
  59223. 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];
  59224. 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];
  59225. 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];
  59226. 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];
  59227. 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];
  59228. }
  59229. }
  59230. else {
  59231. this._particle._globalPosition.x = this._particle.position.x;
  59232. this._particle._globalPosition.y = this._particle.position.y;
  59233. this._particle._globalPosition.z = this._particle.position.z;
  59234. if (this._computeParticleRotation || this.billboard) {
  59235. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59236. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59237. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59238. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59239. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59240. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59241. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59242. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59243. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59244. }
  59245. }
  59246. if (this._particle.translateFromPivot) {
  59247. this._pivotBackTranslation.x = 0.0;
  59248. this._pivotBackTranslation.y = 0.0;
  59249. this._pivotBackTranslation.z = 0.0;
  59250. }
  59251. else {
  59252. this._pivotBackTranslation.x = this._scaledPivot.x;
  59253. this._pivotBackTranslation.y = this._scaledPivot.y;
  59254. this._pivotBackTranslation.z = this._scaledPivot.z;
  59255. }
  59256. // particle vertex loop
  59257. for (pt = 0; pt < this._shape.length; pt++) {
  59258. idx = index + pt * 3;
  59259. colidx = colorIndex + pt * 4;
  59260. uvidx = uvIndex + pt * 2;
  59261. this._vertex.x = this._shape[pt].x;
  59262. this._vertex.y = this._shape[pt].y;
  59263. this._vertex.z = this._shape[pt].z;
  59264. if (this._computeParticleVertex) {
  59265. this.updateParticleVertex(this._particle, this._vertex, pt);
  59266. }
  59267. // positions
  59268. this._vertex.x *= this._particle.scaling.x;
  59269. this._vertex.y *= this._particle.scaling.y;
  59270. this._vertex.z *= this._particle.scaling.z;
  59271. this._vertex.x -= this._scaledPivot.x;
  59272. this._vertex.y -= this._scaledPivot.y;
  59273. this._vertex.z -= this._scaledPivot.z;
  59274. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59275. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59276. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59277. this._rotated.x += this._pivotBackTranslation.x;
  59278. this._rotated.y += this._pivotBackTranslation.y;
  59279. this._rotated.z += this._pivotBackTranslation.z;
  59280. 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;
  59281. 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;
  59282. 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;
  59283. if (this._computeBoundingBox) {
  59284. if (this._positions32[idx] < this._minimum.x) {
  59285. this._minimum.x = this._positions32[idx];
  59286. }
  59287. if (this._positions32[idx] > this._maximum.x) {
  59288. this._maximum.x = this._positions32[idx];
  59289. }
  59290. if (this._positions32[idx + 1] < this._minimum.y) {
  59291. this._minimum.y = this._positions32[idx + 1];
  59292. }
  59293. if (this._positions32[idx + 1] > this._maximum.y) {
  59294. this._maximum.y = this._positions32[idx + 1];
  59295. }
  59296. if (this._positions32[idx + 2] < this._minimum.z) {
  59297. this._minimum.z = this._positions32[idx + 2];
  59298. }
  59299. if (this._positions32[idx + 2] > this._maximum.z) {
  59300. this._maximum.z = this._positions32[idx + 2];
  59301. }
  59302. }
  59303. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59304. if (!this._computeParticleVertex) {
  59305. this._normal.x = this._fixedNormal32[idx];
  59306. this._normal.y = this._fixedNormal32[idx + 1];
  59307. this._normal.z = this._fixedNormal32[idx + 2];
  59308. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59309. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59310. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59311. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59312. 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;
  59313. 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;
  59314. }
  59315. if (this._computeParticleColor && this._particle.color) {
  59316. this._colors32[colidx] = this._particle.color.r;
  59317. this._colors32[colidx + 1] = this._particle.color.g;
  59318. this._colors32[colidx + 2] = this._particle.color.b;
  59319. this._colors32[colidx + 3] = this._particle.color.a;
  59320. }
  59321. if (this._computeParticleTexture) {
  59322. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59323. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59324. }
  59325. }
  59326. }
  59327. // particle just set invisible : scaled to zero and positioned at the origin
  59328. else {
  59329. this._particle._stillInvisible = true; // mark the particle as invisible
  59330. for (pt = 0; pt < this._shape.length; pt++) {
  59331. idx = index + pt * 3;
  59332. colidx = colorIndex + pt * 4;
  59333. uvidx = uvIndex + pt * 2;
  59334. this._positions32[idx] = 0.0;
  59335. this._positions32[idx + 1] = 0.0;
  59336. this._positions32[idx + 2] = 0.0;
  59337. this._normals32[idx] = 0.0;
  59338. this._normals32[idx + 1] = 0.0;
  59339. this._normals32[idx + 2] = 0.0;
  59340. if (this._computeParticleColor && this._particle.color) {
  59341. this._colors32[colidx] = this._particle.color.r;
  59342. this._colors32[colidx + 1] = this._particle.color.g;
  59343. this._colors32[colidx + 2] = this._particle.color.b;
  59344. this._colors32[colidx + 3] = this._particle.color.a;
  59345. }
  59346. if (this._computeParticleTexture) {
  59347. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59348. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59349. }
  59350. }
  59351. }
  59352. // if the particle intersections must be computed : update the bbInfo
  59353. if (this._particlesIntersect) {
  59354. var bInfo = this._particle._boundingInfo;
  59355. var bBox = bInfo.boundingBox;
  59356. var bSphere = bInfo.boundingSphere;
  59357. if (!this._bSphereOnly) {
  59358. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59359. for (var b = 0; b < bBox.vectors.length; b++) {
  59360. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59361. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59362. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59363. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59364. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59365. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59366. 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;
  59367. 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;
  59368. 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;
  59369. }
  59370. bBox._update(this.mesh._worldMatrix);
  59371. }
  59372. // place and scale the particle bouding sphere in the SPS local system, then update it
  59373. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59374. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59375. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59376. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59377. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59378. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59379. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59380. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59381. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59382. 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));
  59383. bSphere._update(this.mesh._worldMatrix);
  59384. }
  59385. // increment indexes for the next particle
  59386. index = idx + 3;
  59387. colorIndex = colidx + 4;
  59388. uvIndex = uvidx + 2;
  59389. }
  59390. // if the VBO must be updated
  59391. if (update) {
  59392. if (this._computeParticleColor) {
  59393. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59394. }
  59395. if (this._computeParticleTexture) {
  59396. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59397. }
  59398. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59399. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59400. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59401. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59402. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59403. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59404. for (var i = 0; i < this._normals32.length; i++) {
  59405. this._fixedNormal32[i] = this._normals32[i];
  59406. }
  59407. }
  59408. if (!this.mesh.areNormalsFrozen) {
  59409. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59410. }
  59411. }
  59412. if (this._depthSort && this._depthSortParticles) {
  59413. this.depthSortedParticles.sort(this._depthSortFunction);
  59414. var dspl = this.depthSortedParticles.length;
  59415. var sorted = 0;
  59416. var lind = 0;
  59417. var sind = 0;
  59418. var sid = 0;
  59419. for (sorted = 0; sorted < dspl; sorted++) {
  59420. lind = this.depthSortedParticles[sorted].indicesLength;
  59421. sind = this.depthSortedParticles[sorted].ind;
  59422. for (var i = 0; i < lind; i++) {
  59423. this._indices32[sid] = this._indices[sind + i];
  59424. sid++;
  59425. }
  59426. }
  59427. this.mesh.updateIndices(this._indices32);
  59428. }
  59429. }
  59430. if (this._computeBoundingBox) {
  59431. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59432. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59433. }
  59434. this.afterUpdateParticles(start, end, update);
  59435. return this;
  59436. };
  59437. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59438. this._halfroll = this._roll * 0.5;
  59439. this._halfpitch = this._pitch * 0.5;
  59440. this._halfyaw = this._yaw * 0.5;
  59441. this._sinRoll = Math.sin(this._halfroll);
  59442. this._cosRoll = Math.cos(this._halfroll);
  59443. this._sinPitch = Math.sin(this._halfpitch);
  59444. this._cosPitch = Math.cos(this._halfpitch);
  59445. this._sinYaw = Math.sin(this._halfyaw);
  59446. this._cosYaw = Math.cos(this._halfyaw);
  59447. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59448. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59449. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59450. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59451. };
  59452. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59453. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59454. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59455. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59456. this._rotMatrix.m[3] = 0;
  59457. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59458. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59459. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59460. this._rotMatrix.m[7] = 0;
  59461. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59462. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59463. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59464. this._rotMatrix.m[11] = 0;
  59465. this._rotMatrix.m[12] = 0;
  59466. this._rotMatrix.m[13] = 0;
  59467. this._rotMatrix.m[14] = 0;
  59468. this._rotMatrix.m[15] = 1.0;
  59469. };
  59470. /**
  59471. * Disposes the SPS.
  59472. */
  59473. SolidParticleSystem.prototype.dispose = function () {
  59474. this.mesh.dispose();
  59475. this.vars = null;
  59476. // drop references to internal big arrays for the GC
  59477. this._positions = null;
  59478. this._indices = null;
  59479. this._normals = null;
  59480. this._uvs = null;
  59481. this._colors = null;
  59482. this._indices32 = null;
  59483. this._positions32 = null;
  59484. this._normals32 = null;
  59485. this._fixedNormal32 = null;
  59486. this._uvs32 = null;
  59487. this._colors32 = null;
  59488. this.pickedParticles = null;
  59489. };
  59490. /**
  59491. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59492. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59493. * @returns the SPS.
  59494. */
  59495. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59496. if (!this._isVisibilityBoxLocked) {
  59497. this.mesh.refreshBoundingInfo();
  59498. }
  59499. return this;
  59500. };
  59501. /**
  59502. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59503. * @param size the size (float) of the visibility box
  59504. * note : this doesn't lock the SPS mesh bounding box.
  59505. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59506. */
  59507. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59508. var vis = size / 2;
  59509. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59510. };
  59511. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59512. /**
  59513. * Gets whether the SPS as always visible or not
  59514. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59515. */
  59516. get: function () {
  59517. return this._alwaysVisible;
  59518. },
  59519. /**
  59520. * Sets the SPS as always visible or not
  59521. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59522. */
  59523. set: function (val) {
  59524. this._alwaysVisible = val;
  59525. this.mesh.alwaysSelectAsActiveMesh = val;
  59526. },
  59527. enumerable: true,
  59528. configurable: true
  59529. });
  59530. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59531. /**
  59532. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59533. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59534. */
  59535. get: function () {
  59536. return this._isVisibilityBoxLocked;
  59537. },
  59538. /**
  59539. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59540. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59541. */
  59542. set: function (val) {
  59543. this._isVisibilityBoxLocked = val;
  59544. var boundingInfo = this.mesh.getBoundingInfo();
  59545. boundingInfo.isLocked = val;
  59546. },
  59547. enumerable: true,
  59548. configurable: true
  59549. });
  59550. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59551. /**
  59552. * Gets if `setParticles()` computes the particle rotations or not.
  59553. * Default value : true. The SPS is faster when it's set to false.
  59554. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59555. */
  59556. get: function () {
  59557. return this._computeParticleRotation;
  59558. },
  59559. /**
  59560. * Tells to `setParticles()` to compute the particle rotations or not.
  59561. * Default value : true. The SPS is faster when it's set to false.
  59562. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59563. */
  59564. set: function (val) {
  59565. this._computeParticleRotation = val;
  59566. },
  59567. enumerable: true,
  59568. configurable: true
  59569. });
  59570. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59571. /**
  59572. * Gets if `setParticles()` computes the particle colors or not.
  59573. * Default value : true. The SPS is faster when it's set to false.
  59574. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59575. */
  59576. get: function () {
  59577. return this._computeParticleColor;
  59578. },
  59579. /**
  59580. * Tells to `setParticles()` to compute the particle colors or not.
  59581. * Default value : true. The SPS is faster when it's set to false.
  59582. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59583. */
  59584. set: function (val) {
  59585. this._computeParticleColor = val;
  59586. },
  59587. enumerable: true,
  59588. configurable: true
  59589. });
  59590. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59591. /**
  59592. * Gets if `setParticles()` computes the particle textures or not.
  59593. * Default value : true. The SPS is faster when it's set to false.
  59594. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59595. */
  59596. get: function () {
  59597. return this._computeParticleTexture;
  59598. },
  59599. set: function (val) {
  59600. this._computeParticleTexture = val;
  59601. },
  59602. enumerable: true,
  59603. configurable: true
  59604. });
  59605. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59606. /**
  59607. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59608. * Default value : false. The SPS is faster when it's set to false.
  59609. * Note : the particle custom vertex positions aren't stored values.
  59610. */
  59611. get: function () {
  59612. return this._computeParticleVertex;
  59613. },
  59614. /**
  59615. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59616. * Default value : false. The SPS is faster when it's set to false.
  59617. * Note : the particle custom vertex positions aren't stored values.
  59618. */
  59619. set: function (val) {
  59620. this._computeParticleVertex = val;
  59621. },
  59622. enumerable: true,
  59623. configurable: true
  59624. });
  59625. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59626. /**
  59627. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59628. */
  59629. get: function () {
  59630. return this._computeBoundingBox;
  59631. },
  59632. /**
  59633. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59634. */
  59635. set: function (val) {
  59636. this._computeBoundingBox = val;
  59637. },
  59638. enumerable: true,
  59639. configurable: true
  59640. });
  59641. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59642. /**
  59643. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59644. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59645. * Default : `true`
  59646. */
  59647. get: function () {
  59648. return this._depthSortParticles;
  59649. },
  59650. /**
  59651. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59652. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59653. * Default : `true`
  59654. */
  59655. set: function (val) {
  59656. this._depthSortParticles = val;
  59657. },
  59658. enumerable: true,
  59659. configurable: true
  59660. });
  59661. // =======================================================================
  59662. // Particle behavior logic
  59663. // these following methods may be overwritten by the user to fit his needs
  59664. /**
  59665. * This function does nothing. It may be overwritten to set all the particle first values.
  59666. * The SPS doesn't call this function, you may have to call it by your own.
  59667. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59668. */
  59669. SolidParticleSystem.prototype.initParticles = function () {
  59670. };
  59671. /**
  59672. * This function does nothing. It may be overwritten to recycle a particle.
  59673. * The SPS doesn't call this function, you may have to call it by your own.
  59674. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59675. * @param particle The particle to recycle
  59676. * @returns the recycled particle
  59677. */
  59678. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59679. return particle;
  59680. };
  59681. /**
  59682. * Updates a particle : this function should be overwritten by the user.
  59683. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59684. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59685. * @example : just set a particle position or velocity and recycle conditions
  59686. * @param particle The particle to update
  59687. * @returns the updated particle
  59688. */
  59689. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59690. return particle;
  59691. };
  59692. /**
  59693. * Updates a vertex of a particle : it can be overwritten by the user.
  59694. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59695. * @param particle the current particle
  59696. * @param vertex the current index of the current particle
  59697. * @param pt the index of the current vertex in the particle shape
  59698. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59699. * @example : just set a vertex particle position
  59700. * @returns the updated vertex
  59701. */
  59702. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59703. return vertex;
  59704. };
  59705. /**
  59706. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59707. * This does nothing and may be overwritten by the user.
  59708. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59709. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59710. * @param update the boolean update value actually passed to setParticles()
  59711. */
  59712. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59713. };
  59714. /**
  59715. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59716. * This will be passed three parameters.
  59717. * This does nothing and may be overwritten by the user.
  59718. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59719. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59720. * @param update the boolean update value actually passed to setParticles()
  59721. */
  59722. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59723. };
  59724. return SolidParticleSystem;
  59725. }());
  59726. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59727. })(BABYLON || (BABYLON = {}));
  59728. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59729. var BABYLON;
  59730. (function (BABYLON) {
  59731. var ShaderMaterial = /** @class */ (function (_super) {
  59732. __extends(ShaderMaterial, _super);
  59733. function ShaderMaterial(name, scene, shaderPath, options) {
  59734. var _this = _super.call(this, name, scene) || this;
  59735. _this._textures = {};
  59736. _this._textureArrays = {};
  59737. _this._floats = {};
  59738. _this._ints = {};
  59739. _this._floatsArrays = {};
  59740. _this._colors3 = {};
  59741. _this._colors3Arrays = {};
  59742. _this._colors4 = {};
  59743. _this._vectors2 = {};
  59744. _this._vectors3 = {};
  59745. _this._vectors4 = {};
  59746. _this._matrices = {};
  59747. _this._matrices3x3 = {};
  59748. _this._matrices2x2 = {};
  59749. _this._vectors2Arrays = {};
  59750. _this._vectors3Arrays = {};
  59751. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59752. _this._shaderPath = shaderPath;
  59753. options.needAlphaBlending = options.needAlphaBlending || false;
  59754. options.needAlphaTesting = options.needAlphaTesting || false;
  59755. options.attributes = options.attributes || ["position", "normal", "uv"];
  59756. options.uniforms = options.uniforms || ["worldViewProjection"];
  59757. options.uniformBuffers = options.uniformBuffers || [];
  59758. options.samplers = options.samplers || [];
  59759. options.defines = options.defines || [];
  59760. _this._options = options;
  59761. return _this;
  59762. }
  59763. ShaderMaterial.prototype.getClassName = function () {
  59764. return "ShaderMaterial";
  59765. };
  59766. ShaderMaterial.prototype.needAlphaBlending = function () {
  59767. return this._options.needAlphaBlending;
  59768. };
  59769. ShaderMaterial.prototype.needAlphaTesting = function () {
  59770. return this._options.needAlphaTesting;
  59771. };
  59772. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59773. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59774. this._options.uniforms.push(uniformName);
  59775. }
  59776. };
  59777. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59778. if (this._options.samplers.indexOf(name) === -1) {
  59779. this._options.samplers.push(name);
  59780. }
  59781. this._textures[name] = texture;
  59782. return this;
  59783. };
  59784. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59785. if (this._options.samplers.indexOf(name) === -1) {
  59786. this._options.samplers.push(name);
  59787. }
  59788. this._checkUniform(name);
  59789. this._textureArrays[name] = textures;
  59790. return this;
  59791. };
  59792. ShaderMaterial.prototype.setFloat = function (name, value) {
  59793. this._checkUniform(name);
  59794. this._floats[name] = value;
  59795. return this;
  59796. };
  59797. ShaderMaterial.prototype.setInt = function (name, value) {
  59798. this._checkUniform(name);
  59799. this._ints[name] = value;
  59800. return this;
  59801. };
  59802. ShaderMaterial.prototype.setFloats = function (name, value) {
  59803. this._checkUniform(name);
  59804. this._floatsArrays[name] = value;
  59805. return this;
  59806. };
  59807. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59808. this._checkUniform(name);
  59809. this._colors3[name] = value;
  59810. return this;
  59811. };
  59812. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59813. this._checkUniform(name);
  59814. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59815. color.toArray(arr, arr.length);
  59816. return arr;
  59817. }, []);
  59818. return this;
  59819. };
  59820. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59821. this._checkUniform(name);
  59822. this._colors4[name] = value;
  59823. return this;
  59824. };
  59825. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59826. this._checkUniform(name);
  59827. this._vectors2[name] = value;
  59828. return this;
  59829. };
  59830. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59831. this._checkUniform(name);
  59832. this._vectors3[name] = value;
  59833. return this;
  59834. };
  59835. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59836. this._checkUniform(name);
  59837. this._vectors4[name] = value;
  59838. return this;
  59839. };
  59840. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59841. this._checkUniform(name);
  59842. this._matrices[name] = value;
  59843. return this;
  59844. };
  59845. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59846. this._checkUniform(name);
  59847. this._matrices3x3[name] = value;
  59848. return this;
  59849. };
  59850. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59851. this._checkUniform(name);
  59852. this._matrices2x2[name] = value;
  59853. return this;
  59854. };
  59855. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59856. this._checkUniform(name);
  59857. this._vectors2Arrays[name] = value;
  59858. return this;
  59859. };
  59860. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59861. this._checkUniform(name);
  59862. this._vectors3Arrays[name] = value;
  59863. return this;
  59864. };
  59865. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59866. if (!mesh) {
  59867. return true;
  59868. }
  59869. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59870. return false;
  59871. }
  59872. return false;
  59873. };
  59874. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59875. var scene = this.getScene();
  59876. var engine = scene.getEngine();
  59877. if (!this.checkReadyOnEveryCall) {
  59878. if (this._renderId === scene.getRenderId()) {
  59879. if (this._checkCache(scene, mesh, useInstances)) {
  59880. return true;
  59881. }
  59882. }
  59883. }
  59884. // Instances
  59885. var defines = [];
  59886. var attribs = [];
  59887. var fallbacks = new BABYLON.EffectFallbacks();
  59888. if (useInstances) {
  59889. defines.push("#define INSTANCES");
  59890. }
  59891. for (var index = 0; index < this._options.defines.length; index++) {
  59892. defines.push(this._options.defines[index]);
  59893. }
  59894. for (var index = 0; index < this._options.attributes.length; index++) {
  59895. attribs.push(this._options.attributes[index]);
  59896. }
  59897. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59898. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59899. defines.push("#define VERTEXCOLOR");
  59900. }
  59901. // Bones
  59902. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59903. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59904. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59905. if (mesh.numBoneInfluencers > 4) {
  59906. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59907. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59908. }
  59909. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59910. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59911. fallbacks.addCPUSkinningFallback(0, mesh);
  59912. if (this._options.uniforms.indexOf("mBones") === -1) {
  59913. this._options.uniforms.push("mBones");
  59914. }
  59915. }
  59916. else {
  59917. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59918. }
  59919. // Textures
  59920. for (var name in this._textures) {
  59921. if (!this._textures[name].isReady()) {
  59922. return false;
  59923. }
  59924. }
  59925. // Alpha test
  59926. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59927. defines.push("#define ALPHATEST");
  59928. }
  59929. var previousEffect = this._effect;
  59930. var join = defines.join("\n");
  59931. this._effect = engine.createEffect(this._shaderPath, {
  59932. attributes: attribs,
  59933. uniformsNames: this._options.uniforms,
  59934. uniformBuffersNames: this._options.uniformBuffers,
  59935. samplers: this._options.samplers,
  59936. defines: join,
  59937. fallbacks: fallbacks,
  59938. onCompiled: this.onCompiled,
  59939. onError: this.onError
  59940. }, engine);
  59941. if (!this._effect.isReady()) {
  59942. return false;
  59943. }
  59944. if (previousEffect !== this._effect) {
  59945. scene.resetCachedMaterial();
  59946. }
  59947. this._renderId = scene.getRenderId();
  59948. return true;
  59949. };
  59950. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59951. var scene = this.getScene();
  59952. if (!this._effect) {
  59953. return;
  59954. }
  59955. if (this._options.uniforms.indexOf("world") !== -1) {
  59956. this._effect.setMatrix("world", world);
  59957. }
  59958. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59959. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59960. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59961. }
  59962. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59963. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59964. }
  59965. };
  59966. ShaderMaterial.prototype.bind = function (world, mesh) {
  59967. // Std values
  59968. this.bindOnlyWorldMatrix(world);
  59969. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59970. if (this._options.uniforms.indexOf("view") !== -1) {
  59971. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59972. }
  59973. if (this._options.uniforms.indexOf("projection") !== -1) {
  59974. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59975. }
  59976. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59977. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59978. }
  59979. // Bones
  59980. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59981. var name;
  59982. // Texture
  59983. for (name in this._textures) {
  59984. this._effect.setTexture(name, this._textures[name]);
  59985. }
  59986. // Texture arrays
  59987. for (name in this._textureArrays) {
  59988. this._effect.setTextureArray(name, this._textureArrays[name]);
  59989. }
  59990. // Int
  59991. for (name in this._ints) {
  59992. this._effect.setInt(name, this._ints[name]);
  59993. }
  59994. // Float
  59995. for (name in this._floats) {
  59996. this._effect.setFloat(name, this._floats[name]);
  59997. }
  59998. // Floats
  59999. for (name in this._floatsArrays) {
  60000. this._effect.setArray(name, this._floatsArrays[name]);
  60001. }
  60002. // Color3
  60003. for (name in this._colors3) {
  60004. this._effect.setColor3(name, this._colors3[name]);
  60005. }
  60006. for (name in this._colors3Arrays) {
  60007. this._effect.setArray3(name, this._colors3Arrays[name]);
  60008. }
  60009. // Color4
  60010. for (name in this._colors4) {
  60011. var color = this._colors4[name];
  60012. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  60013. }
  60014. // Vector2
  60015. for (name in this._vectors2) {
  60016. this._effect.setVector2(name, this._vectors2[name]);
  60017. }
  60018. // Vector3
  60019. for (name in this._vectors3) {
  60020. this._effect.setVector3(name, this._vectors3[name]);
  60021. }
  60022. // Vector4
  60023. for (name in this._vectors4) {
  60024. this._effect.setVector4(name, this._vectors4[name]);
  60025. }
  60026. // Matrix
  60027. for (name in this._matrices) {
  60028. this._effect.setMatrix(name, this._matrices[name]);
  60029. }
  60030. // Matrix 3x3
  60031. for (name in this._matrices3x3) {
  60032. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  60033. }
  60034. // Matrix 2x2
  60035. for (name in this._matrices2x2) {
  60036. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  60037. }
  60038. // Vector2Array
  60039. for (name in this._vectors2Arrays) {
  60040. this._effect.setArray2(name, this._vectors2Arrays[name]);
  60041. }
  60042. // Vector3Array
  60043. for (name in this._vectors3Arrays) {
  60044. this._effect.setArray3(name, this._vectors3Arrays[name]);
  60045. }
  60046. }
  60047. this._afterBind(mesh);
  60048. };
  60049. ShaderMaterial.prototype.getActiveTextures = function () {
  60050. var activeTextures = _super.prototype.getActiveTextures.call(this);
  60051. for (var name in this._textures) {
  60052. activeTextures.push(this._textures[name]);
  60053. }
  60054. for (var name in this._textureArrays) {
  60055. var array = this._textureArrays[name];
  60056. for (var index = 0; index < array.length; index++) {
  60057. activeTextures.push(array[index]);
  60058. }
  60059. }
  60060. return activeTextures;
  60061. };
  60062. ShaderMaterial.prototype.hasTexture = function (texture) {
  60063. if (_super.prototype.hasTexture.call(this, texture)) {
  60064. return true;
  60065. }
  60066. for (var name in this._textures) {
  60067. if (this._textures[name] === texture) {
  60068. return true;
  60069. }
  60070. }
  60071. for (var name in this._textureArrays) {
  60072. var array = this._textureArrays[name];
  60073. for (var index = 0; index < array.length; index++) {
  60074. if (array[index] === texture) {
  60075. return true;
  60076. }
  60077. }
  60078. }
  60079. return false;
  60080. };
  60081. ShaderMaterial.prototype.clone = function (name) {
  60082. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  60083. return newShaderMaterial;
  60084. };
  60085. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  60086. if (forceDisposeTextures) {
  60087. var name;
  60088. for (name in this._textures) {
  60089. this._textures[name].dispose();
  60090. }
  60091. for (name in this._textureArrays) {
  60092. var array = this._textureArrays[name];
  60093. for (var index = 0; index < array.length; index++) {
  60094. array[index].dispose();
  60095. }
  60096. }
  60097. }
  60098. this._textures = {};
  60099. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  60100. };
  60101. ShaderMaterial.prototype.serialize = function () {
  60102. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60103. serializationObject.customType = "BABYLON.ShaderMaterial";
  60104. serializationObject.options = this._options;
  60105. serializationObject.shaderPath = this._shaderPath;
  60106. var name;
  60107. // Texture
  60108. serializationObject.textures = {};
  60109. for (name in this._textures) {
  60110. serializationObject.textures[name] = this._textures[name].serialize();
  60111. }
  60112. // Texture arrays
  60113. serializationObject.textureArrays = {};
  60114. for (name in this._textureArrays) {
  60115. serializationObject.textureArrays[name] = [];
  60116. var array = this._textureArrays[name];
  60117. for (var index = 0; index < array.length; index++) {
  60118. serializationObject.textureArrays[name].push(array[index].serialize());
  60119. }
  60120. }
  60121. // Float
  60122. serializationObject.floats = {};
  60123. for (name in this._floats) {
  60124. serializationObject.floats[name] = this._floats[name];
  60125. }
  60126. // Float s
  60127. serializationObject.FloatArrays = {};
  60128. for (name in this._floatsArrays) {
  60129. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  60130. }
  60131. // Color3
  60132. serializationObject.colors3 = {};
  60133. for (name in this._colors3) {
  60134. serializationObject.colors3[name] = this._colors3[name].asArray();
  60135. }
  60136. // Color3 array
  60137. serializationObject.colors3Arrays = {};
  60138. for (name in this._colors3Arrays) {
  60139. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  60140. }
  60141. // Color4
  60142. serializationObject.colors4 = {};
  60143. for (name in this._colors4) {
  60144. serializationObject.colors4[name] = this._colors4[name].asArray();
  60145. }
  60146. // Vector2
  60147. serializationObject.vectors2 = {};
  60148. for (name in this._vectors2) {
  60149. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  60150. }
  60151. // Vector3
  60152. serializationObject.vectors3 = {};
  60153. for (name in this._vectors3) {
  60154. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  60155. }
  60156. // Vector4
  60157. serializationObject.vectors4 = {};
  60158. for (name in this._vectors4) {
  60159. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  60160. }
  60161. // Matrix
  60162. serializationObject.matrices = {};
  60163. for (name in this._matrices) {
  60164. serializationObject.matrices[name] = this._matrices[name].asArray();
  60165. }
  60166. // Matrix 3x3
  60167. serializationObject.matrices3x3 = {};
  60168. for (name in this._matrices3x3) {
  60169. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60170. }
  60171. // Matrix 2x2
  60172. serializationObject.matrices2x2 = {};
  60173. for (name in this._matrices2x2) {
  60174. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60175. }
  60176. // Vector2Array
  60177. serializationObject.vectors2Arrays = {};
  60178. for (name in this._vectors2Arrays) {
  60179. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60180. }
  60181. // Vector3Array
  60182. serializationObject.vectors3Arrays = {};
  60183. for (name in this._vectors3Arrays) {
  60184. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60185. }
  60186. return serializationObject;
  60187. };
  60188. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60189. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60190. var name;
  60191. // Texture
  60192. for (name in source.textures) {
  60193. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60194. }
  60195. // Texture arrays
  60196. for (name in source.textureArrays) {
  60197. var array = source.textureArrays[name];
  60198. var textureArray = new Array();
  60199. for (var index = 0; index < array.length; index++) {
  60200. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60201. }
  60202. material.setTextureArray(name, textureArray);
  60203. }
  60204. // Float
  60205. for (name in source.floats) {
  60206. material.setFloat(name, source.floats[name]);
  60207. }
  60208. // Float s
  60209. for (name in source.floatsArrays) {
  60210. material.setFloats(name, source.floatsArrays[name]);
  60211. }
  60212. // Color3
  60213. for (name in source.colors3) {
  60214. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60215. }
  60216. // Color3 arrays
  60217. for (name in source.colors3Arrays) {
  60218. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60219. if (i % 3 === 0) {
  60220. arr.push([num]);
  60221. }
  60222. else {
  60223. arr[arr.length - 1].push(num);
  60224. }
  60225. return arr;
  60226. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60227. material.setColor3Array(name, colors);
  60228. }
  60229. // Color4
  60230. for (name in source.colors4) {
  60231. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60232. }
  60233. // Vector2
  60234. for (name in source.vectors2) {
  60235. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60236. }
  60237. // Vector3
  60238. for (name in source.vectors3) {
  60239. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60240. }
  60241. // Vector4
  60242. for (name in source.vectors4) {
  60243. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60244. }
  60245. // Matrix
  60246. for (name in source.matrices) {
  60247. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60248. }
  60249. // Matrix 3x3
  60250. for (name in source.matrices3x3) {
  60251. material.setMatrix3x3(name, source.matrices3x3[name]);
  60252. }
  60253. // Matrix 2x2
  60254. for (name in source.matrices2x2) {
  60255. material.setMatrix2x2(name, source.matrices2x2[name]);
  60256. }
  60257. // Vector2Array
  60258. for (name in source.vectors2Arrays) {
  60259. material.setArray2(name, source.vectors2Arrays[name]);
  60260. }
  60261. // Vector3Array
  60262. for (name in source.vectors3Arrays) {
  60263. material.setArray3(name, source.vectors3Arrays[name]);
  60264. }
  60265. return material;
  60266. };
  60267. return ShaderMaterial;
  60268. }(BABYLON.Material));
  60269. BABYLON.ShaderMaterial = ShaderMaterial;
  60270. })(BABYLON || (BABYLON = {}));
  60271. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60272. var BABYLON;
  60273. (function (BABYLON) {
  60274. var GroundMesh = /** @class */ (function (_super) {
  60275. __extends(GroundMesh, _super);
  60276. function GroundMesh(name, scene) {
  60277. var _this = _super.call(this, name, scene) || this;
  60278. _this.generateOctree = false;
  60279. return _this;
  60280. }
  60281. GroundMesh.prototype.getClassName = function () {
  60282. return "GroundMesh";
  60283. };
  60284. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60285. get: function () {
  60286. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60287. },
  60288. enumerable: true,
  60289. configurable: true
  60290. });
  60291. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60292. get: function () {
  60293. return this._subdivisionsX;
  60294. },
  60295. enumerable: true,
  60296. configurable: true
  60297. });
  60298. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60299. get: function () {
  60300. return this._subdivisionsY;
  60301. },
  60302. enumerable: true,
  60303. configurable: true
  60304. });
  60305. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60306. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60307. this._subdivisionsX = chunksCount;
  60308. this._subdivisionsY = chunksCount;
  60309. this.subdivide(chunksCount);
  60310. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60311. };
  60312. /**
  60313. * Returns a height (y) value in the Worl system :
  60314. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60315. * Returns the ground y position if (x, z) are outside the ground surface.
  60316. */
  60317. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60318. var world = this.getWorldMatrix();
  60319. var invMat = BABYLON.Tmp.Matrix[5];
  60320. world.invertToRef(invMat);
  60321. var tmpVect = BABYLON.Tmp.Vector3[8];
  60322. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60323. x = tmpVect.x;
  60324. z = tmpVect.z;
  60325. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60326. return this.position.y;
  60327. }
  60328. if (!this._heightQuads || this._heightQuads.length == 0) {
  60329. this._initHeightQuads();
  60330. this._computeHeightQuads();
  60331. }
  60332. var facet = this._getFacetAt(x, z);
  60333. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60334. // return y in the World system
  60335. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60336. return tmpVect.y;
  60337. };
  60338. /**
  60339. * Returns a normalized vector (Vector3) orthogonal to the ground
  60340. * at the ground coordinates (x, z) expressed in the World system.
  60341. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60342. */
  60343. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60344. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60345. this.getNormalAtCoordinatesToRef(x, z, normal);
  60346. return normal;
  60347. };
  60348. /**
  60349. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60350. * at the ground coordinates (x, z) expressed in the World system.
  60351. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60352. * Returns the GroundMesh.
  60353. */
  60354. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60355. var world = this.getWorldMatrix();
  60356. var tmpMat = BABYLON.Tmp.Matrix[5];
  60357. world.invertToRef(tmpMat);
  60358. var tmpVect = BABYLON.Tmp.Vector3[8];
  60359. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60360. x = tmpVect.x;
  60361. z = tmpVect.z;
  60362. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60363. return this;
  60364. }
  60365. if (!this._heightQuads || this._heightQuads.length == 0) {
  60366. this._initHeightQuads();
  60367. this._computeHeightQuads();
  60368. }
  60369. var facet = this._getFacetAt(x, z);
  60370. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60371. return this;
  60372. };
  60373. /**
  60374. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60375. * if the ground has been updated.
  60376. * This can be used in the render loop.
  60377. * Returns the GroundMesh.
  60378. */
  60379. GroundMesh.prototype.updateCoordinateHeights = function () {
  60380. if (!this._heightQuads || this._heightQuads.length == 0) {
  60381. this._initHeightQuads();
  60382. }
  60383. this._computeHeightQuads();
  60384. return this;
  60385. };
  60386. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60387. GroundMesh.prototype._getFacetAt = function (x, z) {
  60388. // retrieve col and row from x, z coordinates in the ground local system
  60389. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60390. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60391. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60392. var facet;
  60393. if (z < quad.slope.x * x + quad.slope.y) {
  60394. facet = quad.facet1;
  60395. }
  60396. else {
  60397. facet = quad.facet2;
  60398. }
  60399. return facet;
  60400. };
  60401. // Creates and populates the heightMap array with "facet" elements :
  60402. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60403. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60404. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60405. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60406. // Returns the GroundMesh.
  60407. GroundMesh.prototype._initHeightQuads = function () {
  60408. var subdivisionsX = this._subdivisionsX;
  60409. var subdivisionsY = this._subdivisionsY;
  60410. this._heightQuads = new Array();
  60411. for (var row = 0; row < subdivisionsY; row++) {
  60412. for (var col = 0; col < subdivisionsX; col++) {
  60413. 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) };
  60414. this._heightQuads[row * subdivisionsX + col] = quad;
  60415. }
  60416. }
  60417. return this;
  60418. };
  60419. // Compute each quad element values and update the the heightMap array :
  60420. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60421. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60422. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60423. // Returns the GroundMesh.
  60424. GroundMesh.prototype._computeHeightQuads = function () {
  60425. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60426. if (!positions) {
  60427. return this;
  60428. }
  60429. var v1 = BABYLON.Tmp.Vector3[3];
  60430. var v2 = BABYLON.Tmp.Vector3[2];
  60431. var v3 = BABYLON.Tmp.Vector3[1];
  60432. var v4 = BABYLON.Tmp.Vector3[0];
  60433. var v1v2 = BABYLON.Tmp.Vector3[4];
  60434. var v1v3 = BABYLON.Tmp.Vector3[5];
  60435. var v1v4 = BABYLON.Tmp.Vector3[6];
  60436. var norm1 = BABYLON.Tmp.Vector3[7];
  60437. var norm2 = BABYLON.Tmp.Vector3[8];
  60438. var i = 0;
  60439. var j = 0;
  60440. var k = 0;
  60441. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60442. var h = 0;
  60443. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60444. var d2 = 0;
  60445. var subdivisionsX = this._subdivisionsX;
  60446. var subdivisionsY = this._subdivisionsY;
  60447. for (var row = 0; row < subdivisionsY; row++) {
  60448. for (var col = 0; col < subdivisionsX; col++) {
  60449. i = col * 3;
  60450. j = row * (subdivisionsX + 1) * 3;
  60451. k = (row + 1) * (subdivisionsX + 1) * 3;
  60452. v1.x = positions[j + i];
  60453. v1.y = positions[j + i + 1];
  60454. v1.z = positions[j + i + 2];
  60455. v2.x = positions[j + i + 3];
  60456. v2.y = positions[j + i + 4];
  60457. v2.z = positions[j + i + 5];
  60458. v3.x = positions[k + i];
  60459. v3.y = positions[k + i + 1];
  60460. v3.z = positions[k + i + 2];
  60461. v4.x = positions[k + i + 3];
  60462. v4.y = positions[k + i + 4];
  60463. v4.z = positions[k + i + 5];
  60464. // 2D slope V1V4
  60465. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60466. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60467. // facet equations :
  60468. // we compute each facet normal vector
  60469. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60470. // we compute the value d by applying the equation to v1 which belongs to the plane
  60471. // then we store the facet equation in a Vector4
  60472. v2.subtractToRef(v1, v1v2);
  60473. v3.subtractToRef(v1, v1v3);
  60474. v4.subtractToRef(v1, v1v4);
  60475. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60476. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60477. norm1.normalize();
  60478. norm2.normalize();
  60479. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60480. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60481. var quad = this._heightQuads[row * subdivisionsX + col];
  60482. quad.slope.copyFromFloats(cd, h);
  60483. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60484. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60485. }
  60486. }
  60487. return this;
  60488. };
  60489. GroundMesh.prototype.serialize = function (serializationObject) {
  60490. _super.prototype.serialize.call(this, serializationObject);
  60491. serializationObject.subdivisionsX = this._subdivisionsX;
  60492. serializationObject.subdivisionsY = this._subdivisionsY;
  60493. serializationObject.minX = this._minX;
  60494. serializationObject.maxX = this._maxX;
  60495. serializationObject.minZ = this._minZ;
  60496. serializationObject.maxZ = this._maxZ;
  60497. serializationObject.width = this._width;
  60498. serializationObject.height = this._height;
  60499. };
  60500. GroundMesh.Parse = function (parsedMesh, scene) {
  60501. var result = new GroundMesh(parsedMesh.name, scene);
  60502. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60503. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60504. result._minX = parsedMesh.minX;
  60505. result._maxX = parsedMesh.maxX;
  60506. result._minZ = parsedMesh.minZ;
  60507. result._maxZ = parsedMesh.maxZ;
  60508. result._width = parsedMesh.width;
  60509. result._height = parsedMesh.height;
  60510. return result;
  60511. };
  60512. return GroundMesh;
  60513. }(BABYLON.Mesh));
  60514. BABYLON.GroundMesh = GroundMesh;
  60515. })(BABYLON || (BABYLON = {}));
  60516. //# sourceMappingURL=babylon.groundMesh.js.map
  60517. var BABYLON;
  60518. (function (BABYLON) {
  60519. /**
  60520. * Creates an instance based on a source mesh.
  60521. */
  60522. var InstancedMesh = /** @class */ (function (_super) {
  60523. __extends(InstancedMesh, _super);
  60524. function InstancedMesh(name, source) {
  60525. var _this = _super.call(this, name, source.getScene()) || this;
  60526. source.instances.push(_this);
  60527. _this._sourceMesh = source;
  60528. _this.position.copyFrom(source.position);
  60529. _this.rotation.copyFrom(source.rotation);
  60530. _this.scaling.copyFrom(source.scaling);
  60531. if (source.rotationQuaternion) {
  60532. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60533. }
  60534. _this.infiniteDistance = source.infiniteDistance;
  60535. _this.setPivotMatrix(source.getPivotMatrix());
  60536. _this.refreshBoundingInfo();
  60537. _this._syncSubMeshes();
  60538. return _this;
  60539. }
  60540. /**
  60541. * Returns the string "InstancedMesh".
  60542. */
  60543. InstancedMesh.prototype.getClassName = function () {
  60544. return "InstancedMesh";
  60545. };
  60546. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60547. // Methods
  60548. get: function () {
  60549. return this._sourceMesh.receiveShadows;
  60550. },
  60551. enumerable: true,
  60552. configurable: true
  60553. });
  60554. Object.defineProperty(InstancedMesh.prototype, "material", {
  60555. get: function () {
  60556. return this._sourceMesh.material;
  60557. },
  60558. enumerable: true,
  60559. configurable: true
  60560. });
  60561. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60562. get: function () {
  60563. return this._sourceMesh.visibility;
  60564. },
  60565. enumerable: true,
  60566. configurable: true
  60567. });
  60568. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60569. get: function () {
  60570. return this._sourceMesh.skeleton;
  60571. },
  60572. enumerable: true,
  60573. configurable: true
  60574. });
  60575. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60576. get: function () {
  60577. return this._sourceMesh.renderingGroupId;
  60578. },
  60579. set: function (value) {
  60580. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60581. return;
  60582. }
  60583. //no-op with warning
  60584. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60585. },
  60586. enumerable: true,
  60587. configurable: true
  60588. });
  60589. /**
  60590. * Returns the total number of vertices (integer).
  60591. */
  60592. InstancedMesh.prototype.getTotalVertices = function () {
  60593. return this._sourceMesh.getTotalVertices();
  60594. };
  60595. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60596. get: function () {
  60597. return this._sourceMesh;
  60598. },
  60599. enumerable: true,
  60600. configurable: true
  60601. });
  60602. /**
  60603. * Is this node ready to be used/rendered
  60604. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60605. * @return {boolean} is it ready
  60606. */
  60607. InstancedMesh.prototype.isReady = function (completeCheck) {
  60608. if (completeCheck === void 0) { completeCheck = false; }
  60609. return this._sourceMesh.isReady(completeCheck, true);
  60610. };
  60611. /**
  60612. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60613. */
  60614. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60615. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60616. };
  60617. /**
  60618. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60619. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60620. * The `data` are either a numeric array either a Float32Array.
  60621. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60622. * 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).
  60623. * Note that a new underlying VertexBuffer object is created each call.
  60624. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60625. *
  60626. * Possible `kind` values :
  60627. * - BABYLON.VertexBuffer.PositionKind
  60628. * - BABYLON.VertexBuffer.UVKind
  60629. * - BABYLON.VertexBuffer.UV2Kind
  60630. * - BABYLON.VertexBuffer.UV3Kind
  60631. * - BABYLON.VertexBuffer.UV4Kind
  60632. * - BABYLON.VertexBuffer.UV5Kind
  60633. * - BABYLON.VertexBuffer.UV6Kind
  60634. * - BABYLON.VertexBuffer.ColorKind
  60635. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60636. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60637. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60638. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60639. *
  60640. * Returns the Mesh.
  60641. */
  60642. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60643. if (this.sourceMesh) {
  60644. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60645. }
  60646. return this.sourceMesh;
  60647. };
  60648. /**
  60649. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60650. * If the mesh has no geometry, it is simply returned as it is.
  60651. * The `data` are either a numeric array either a Float32Array.
  60652. * No new underlying VertexBuffer object is created.
  60653. * 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.
  60654. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60655. *
  60656. * Possible `kind` values :
  60657. * - BABYLON.VertexBuffer.PositionKind
  60658. * - BABYLON.VertexBuffer.UVKind
  60659. * - BABYLON.VertexBuffer.UV2Kind
  60660. * - BABYLON.VertexBuffer.UV3Kind
  60661. * - BABYLON.VertexBuffer.UV4Kind
  60662. * - BABYLON.VertexBuffer.UV5Kind
  60663. * - BABYLON.VertexBuffer.UV6Kind
  60664. * - BABYLON.VertexBuffer.ColorKind
  60665. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60666. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60667. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60668. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60669. *
  60670. * Returns the Mesh.
  60671. */
  60672. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60673. if (this.sourceMesh) {
  60674. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60675. }
  60676. return this.sourceMesh;
  60677. };
  60678. /**
  60679. * Sets the mesh indices.
  60680. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60681. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60682. * This method creates a new index buffer each call.
  60683. * Returns the Mesh.
  60684. */
  60685. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60686. if (totalVertices === void 0) { totalVertices = null; }
  60687. if (this.sourceMesh) {
  60688. this.sourceMesh.setIndices(indices, totalVertices);
  60689. }
  60690. return this.sourceMesh;
  60691. };
  60692. /**
  60693. * Boolean : True if the mesh owns the requested kind of data.
  60694. */
  60695. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60696. return this._sourceMesh.isVerticesDataPresent(kind);
  60697. };
  60698. /**
  60699. * Returns an array of indices (IndicesArray).
  60700. */
  60701. InstancedMesh.prototype.getIndices = function () {
  60702. return this._sourceMesh.getIndices();
  60703. };
  60704. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60705. get: function () {
  60706. return this._sourceMesh._positions;
  60707. },
  60708. enumerable: true,
  60709. configurable: true
  60710. });
  60711. /**
  60712. * Sets a new updated BoundingInfo to the mesh.
  60713. * Returns the mesh.
  60714. */
  60715. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60716. var meshBB = this._sourceMesh.getBoundingInfo();
  60717. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60718. this._updateBoundingInfo();
  60719. return this;
  60720. };
  60721. InstancedMesh.prototype._preActivate = function () {
  60722. if (this._currentLOD) {
  60723. this._currentLOD._preActivate();
  60724. }
  60725. return this;
  60726. };
  60727. InstancedMesh.prototype._activate = function (renderId) {
  60728. if (this._currentLOD) {
  60729. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60730. }
  60731. return this;
  60732. };
  60733. /**
  60734. * Returns the current associated LOD AbstractMesh.
  60735. */
  60736. InstancedMesh.prototype.getLOD = function (camera) {
  60737. if (!camera) {
  60738. return this;
  60739. }
  60740. var boundingInfo = this.getBoundingInfo();
  60741. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60742. if (this._currentLOD === this.sourceMesh) {
  60743. return this;
  60744. }
  60745. return this._currentLOD;
  60746. };
  60747. InstancedMesh.prototype._syncSubMeshes = function () {
  60748. this.releaseSubMeshes();
  60749. if (this._sourceMesh.subMeshes) {
  60750. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60751. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60752. }
  60753. }
  60754. return this;
  60755. };
  60756. InstancedMesh.prototype._generatePointsArray = function () {
  60757. return this._sourceMesh._generatePointsArray();
  60758. };
  60759. /**
  60760. * Creates a new InstancedMesh from the current mesh.
  60761. * - name (string) : the cloned mesh name
  60762. * - newParent (optional Node) : the optional Node to parent the clone to.
  60763. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60764. *
  60765. * Returns the clone.
  60766. */
  60767. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60768. var result = this._sourceMesh.createInstance(name);
  60769. // Deep copy
  60770. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60771. // Bounding info
  60772. this.refreshBoundingInfo();
  60773. // Parent
  60774. if (newParent) {
  60775. result.parent = newParent;
  60776. }
  60777. if (!doNotCloneChildren) {
  60778. // Children
  60779. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60780. var mesh = this.getScene().meshes[index];
  60781. if (mesh.parent === this) {
  60782. mesh.clone(mesh.name, result);
  60783. }
  60784. }
  60785. }
  60786. result.computeWorldMatrix(true);
  60787. return result;
  60788. };
  60789. /**
  60790. * Disposes the InstancedMesh.
  60791. * Returns nothing.
  60792. */
  60793. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60794. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60795. // Remove from mesh
  60796. var index = this._sourceMesh.instances.indexOf(this);
  60797. this._sourceMesh.instances.splice(index, 1);
  60798. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60799. };
  60800. return InstancedMesh;
  60801. }(BABYLON.AbstractMesh));
  60802. BABYLON.InstancedMesh = InstancedMesh;
  60803. })(BABYLON || (BABYLON = {}));
  60804. //# sourceMappingURL=babylon.instancedMesh.js.map
  60805. var BABYLON;
  60806. (function (BABYLON) {
  60807. var LinesMesh = /** @class */ (function (_super) {
  60808. __extends(LinesMesh, _super);
  60809. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60810. if (scene === void 0) { scene = null; }
  60811. if (parent === void 0) { parent = null; }
  60812. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60813. _this.useVertexColor = useVertexColor;
  60814. _this.useVertexAlpha = useVertexAlpha;
  60815. _this.color = new BABYLON.Color3(1, 1, 1);
  60816. _this.alpha = 1;
  60817. if (source) {
  60818. _this.color = source.color.clone();
  60819. _this.alpha = source.alpha;
  60820. _this.useVertexColor = source.useVertexColor;
  60821. _this.useVertexAlpha = source.useVertexAlpha;
  60822. }
  60823. _this._intersectionThreshold = 0.1;
  60824. var defines = [];
  60825. var options = {
  60826. attributes: [BABYLON.VertexBuffer.PositionKind],
  60827. uniforms: ["world", "viewProjection"],
  60828. needAlphaBlending: true,
  60829. defines: defines
  60830. };
  60831. if (useVertexAlpha === false) {
  60832. options.needAlphaBlending = false;
  60833. }
  60834. if (!useVertexColor) {
  60835. options.uniforms.push("color");
  60836. }
  60837. else {
  60838. options.defines.push("#define VERTEXCOLOR");
  60839. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60840. }
  60841. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60842. return _this;
  60843. }
  60844. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60845. /**
  60846. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60847. * This margin is expressed in world space coordinates, so its value may vary.
  60848. * Default value is 0.1
  60849. * @returns the intersection Threshold value.
  60850. */
  60851. get: function () {
  60852. return this._intersectionThreshold;
  60853. },
  60854. /**
  60855. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60856. * This margin is expressed in world space coordinates, so its value may vary.
  60857. * @param value the new threshold to apply
  60858. */
  60859. set: function (value) {
  60860. if (this._intersectionThreshold === value) {
  60861. return;
  60862. }
  60863. this._intersectionThreshold = value;
  60864. if (this.geometry) {
  60865. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60866. }
  60867. },
  60868. enumerable: true,
  60869. configurable: true
  60870. });
  60871. /**
  60872. * Returns the string "LineMesh"
  60873. */
  60874. LinesMesh.prototype.getClassName = function () {
  60875. return "LinesMesh";
  60876. };
  60877. Object.defineProperty(LinesMesh.prototype, "material", {
  60878. get: function () {
  60879. return this._colorShader;
  60880. },
  60881. set: function (value) {
  60882. // Do nothing
  60883. },
  60884. enumerable: true,
  60885. configurable: true
  60886. });
  60887. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60888. get: function () {
  60889. return false;
  60890. },
  60891. enumerable: true,
  60892. configurable: true
  60893. });
  60894. LinesMesh.prototype.createInstance = function (name) {
  60895. throw new Error("LinesMeshes do not support createInstance.");
  60896. };
  60897. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60898. if (!this._geometry) {
  60899. return this;
  60900. }
  60901. // VBOs
  60902. this._geometry._bind(this._colorShader.getEffect());
  60903. // Color
  60904. if (!this.useVertexColor) {
  60905. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60906. }
  60907. return this;
  60908. };
  60909. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60910. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60911. return this;
  60912. }
  60913. var engine = this.getScene().getEngine();
  60914. // Draw order
  60915. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60916. return this;
  60917. };
  60918. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60919. this._colorShader.dispose();
  60920. _super.prototype.dispose.call(this, doNotRecurse);
  60921. };
  60922. /**
  60923. * Returns a new LineMesh object cloned from the current one.
  60924. */
  60925. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60926. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60927. };
  60928. return LinesMesh;
  60929. }(BABYLON.Mesh));
  60930. BABYLON.LinesMesh = LinesMesh;
  60931. })(BABYLON || (BABYLON = {}));
  60932. //# sourceMappingURL=babylon.linesMesh.js.map
  60933. var BABYLON;
  60934. (function (BABYLON) {
  60935. /**
  60936. * Class containing static functions to help procedurally build meshes
  60937. */
  60938. var MeshBuilder = /** @class */ (function () {
  60939. function MeshBuilder() {
  60940. }
  60941. MeshBuilder.updateSideOrientation = function (orientation) {
  60942. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60943. return BABYLON.Mesh.DOUBLESIDE;
  60944. }
  60945. if (orientation === undefined || orientation === null) {
  60946. return BABYLON.Mesh.FRONTSIDE;
  60947. }
  60948. return orientation;
  60949. };
  60950. /**
  60951. * Creates a box mesh
  60952. * * The parameter `size` sets the size (float) of each box side (default 1)
  60953. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60954. * * 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)
  60955. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60956. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60957. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60958. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60959. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60960. * @param name defines the name of the mesh
  60961. * @param options defines the options used to create the mesh
  60962. * @param scene defines the hosting scene
  60963. * @returns the box mesh
  60964. */
  60965. MeshBuilder.CreateBox = function (name, options, scene) {
  60966. if (scene === void 0) { scene = null; }
  60967. var box = new BABYLON.Mesh(name, scene);
  60968. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60969. box._originalBuilderSideOrientation = options.sideOrientation;
  60970. var vertexData = BABYLON.VertexData.CreateBox(options);
  60971. vertexData.applyToMesh(box, options.updatable);
  60972. return box;
  60973. };
  60974. /**
  60975. * Creates a sphere mesh
  60976. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60977. * * 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`)
  60978. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60979. * * 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
  60980. * * 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)
  60981. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60982. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60983. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60984. * @param name defines the name of the mesh
  60985. * @param options defines the options used to create the mesh
  60986. * @param scene defines the hosting scene
  60987. * @returns the sphere mesh
  60988. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60989. */
  60990. MeshBuilder.CreateSphere = function (name, options, scene) {
  60991. var sphere = new BABYLON.Mesh(name, scene);
  60992. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60993. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60994. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60995. vertexData.applyToMesh(sphere, options.updatable);
  60996. return sphere;
  60997. };
  60998. /**
  60999. * Creates a plane polygonal mesh. By default, this is a disc
  61000. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  61001. * * 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
  61002. * * 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
  61003. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61004. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61005. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61006. * @param name defines the name of the mesh
  61007. * @param options defines the options used to create the mesh
  61008. * @param scene defines the hosting scene
  61009. * @returns the plane polygonal mesh
  61010. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  61011. */
  61012. MeshBuilder.CreateDisc = function (name, options, scene) {
  61013. if (scene === void 0) { scene = null; }
  61014. var disc = new BABYLON.Mesh(name, scene);
  61015. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61016. disc._originalBuilderSideOrientation = options.sideOrientation;
  61017. var vertexData = BABYLON.VertexData.CreateDisc(options);
  61018. vertexData.applyToMesh(disc, options.updatable);
  61019. return disc;
  61020. };
  61021. /**
  61022. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  61023. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  61024. * * 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`)
  61025. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  61026. * * 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
  61027. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61028. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61029. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61030. * @param name defines the name of the mesh
  61031. * @param options defines the options used to create the mesh
  61032. * @param scene defines the hosting scene
  61033. * @returns the icosahedron mesh
  61034. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  61035. */
  61036. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  61037. var sphere = new BABYLON.Mesh(name, scene);
  61038. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61039. sphere._originalBuilderSideOrientation = options.sideOrientation;
  61040. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  61041. vertexData.applyToMesh(sphere, options.updatable);
  61042. return sphere;
  61043. };
  61044. ;
  61045. /**
  61046. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61047. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  61048. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  61049. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  61050. * * 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
  61051. * * 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
  61052. * * 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
  61053. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61054. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61055. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61056. * * 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
  61057. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  61058. * * 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
  61059. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  61060. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61061. * @param name defines the name of the mesh
  61062. * @param options defines the options used to create the mesh
  61063. * @param scene defines the hosting scene
  61064. * @returns the ribbon mesh
  61065. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  61066. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61067. */
  61068. MeshBuilder.CreateRibbon = function (name, options, scene) {
  61069. if (scene === void 0) { scene = null; }
  61070. var pathArray = options.pathArray;
  61071. var closeArray = options.closeArray;
  61072. var closePath = options.closePath;
  61073. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61074. var instance = options.instance;
  61075. var updatable = options.updatable;
  61076. if (instance) { // existing ribbon instance update
  61077. // positionFunction : ribbon case
  61078. // only pathArray and sideOrientation parameters are taken into account for positions update
  61079. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  61080. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  61081. var positionFunction = function (positions) {
  61082. var minlg = pathArray[0].length;
  61083. var i = 0;
  61084. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  61085. for (var si = 1; si <= ns; si++) {
  61086. for (var p = 0; p < pathArray.length; p++) {
  61087. var path = pathArray[p];
  61088. var l = path.length;
  61089. minlg = (minlg < l) ? minlg : l;
  61090. var j = 0;
  61091. while (j < minlg) {
  61092. positions[i] = path[j].x;
  61093. positions[i + 1] = path[j].y;
  61094. positions[i + 2] = path[j].z;
  61095. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  61096. BABYLON.Tmp.Vector3[0].x = path[j].x;
  61097. }
  61098. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  61099. BABYLON.Tmp.Vector3[1].x = path[j].x;
  61100. }
  61101. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  61102. BABYLON.Tmp.Vector3[0].y = path[j].y;
  61103. }
  61104. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  61105. BABYLON.Tmp.Vector3[1].y = path[j].y;
  61106. }
  61107. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  61108. BABYLON.Tmp.Vector3[0].z = path[j].z;
  61109. }
  61110. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  61111. BABYLON.Tmp.Vector3[1].z = path[j].z;
  61112. }
  61113. j++;
  61114. i += 3;
  61115. }
  61116. if (instance._closePath) {
  61117. positions[i] = path[0].x;
  61118. positions[i + 1] = path[0].y;
  61119. positions[i + 2] = path[0].z;
  61120. i += 3;
  61121. }
  61122. }
  61123. }
  61124. };
  61125. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61126. positionFunction(positions);
  61127. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  61128. instance._boundingInfo.update(instance._worldMatrix);
  61129. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61130. if (options.colors) {
  61131. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61132. for (var c = 0; c < options.colors.length; c++) {
  61133. colors[c * 4] = options.colors[c].r;
  61134. colors[c * 4 + 1] = options.colors[c].g;
  61135. colors[c * 4 + 2] = options.colors[c].b;
  61136. colors[c * 4 + 3] = options.colors[c].a;
  61137. }
  61138. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  61139. }
  61140. if (options.uvs) {
  61141. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61142. for (var i = 0; i < options.uvs.length; i++) {
  61143. uvs[i * 2] = options.uvs[i].x;
  61144. uvs[i * 2 + 1] = options.uvs[i].y;
  61145. }
  61146. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  61147. }
  61148. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  61149. var indices = instance.getIndices();
  61150. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61151. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  61152. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  61153. if (instance._closePath) {
  61154. var indexFirst = 0;
  61155. var indexLast = 0;
  61156. for (var p = 0; p < pathArray.length; p++) {
  61157. indexFirst = instance._idx[p] * 3;
  61158. if (p + 1 < pathArray.length) {
  61159. indexLast = (instance._idx[p + 1] - 1) * 3;
  61160. }
  61161. else {
  61162. indexLast = normals.length - 3;
  61163. }
  61164. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  61165. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  61166. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  61167. normals[indexLast] = normals[indexFirst];
  61168. normals[indexLast + 1] = normals[indexFirst + 1];
  61169. normals[indexLast + 2] = normals[indexFirst + 2];
  61170. }
  61171. }
  61172. if (!(instance.areNormalsFrozen)) {
  61173. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61174. }
  61175. }
  61176. return instance;
  61177. }
  61178. else { // new ribbon creation
  61179. var ribbon = new BABYLON.Mesh(name, scene);
  61180. ribbon._originalBuilderSideOrientation = sideOrientation;
  61181. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61182. if (closePath) {
  61183. ribbon._idx = vertexData._idx;
  61184. }
  61185. ribbon._closePath = closePath;
  61186. ribbon._closeArray = closeArray;
  61187. vertexData.applyToMesh(ribbon, updatable);
  61188. return ribbon;
  61189. }
  61190. };
  61191. /**
  61192. * Creates a cylinder or a cone mesh
  61193. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61194. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61195. * * 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.
  61196. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61197. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61198. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61199. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61200. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61201. * * 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).
  61202. * * 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
  61203. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61204. * * 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
  61205. * * 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.
  61206. * * If `enclose` is false, a ring surface is one element.
  61207. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61208. * * 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
  61209. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61210. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61211. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61212. * @param name defines the name of the mesh
  61213. * @param options defines the options used to create the mesh
  61214. * @param scene defines the hosting scene
  61215. * @returns the cylinder mesh
  61216. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61217. */
  61218. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61219. var cylinder = new BABYLON.Mesh(name, scene);
  61220. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61221. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61222. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61223. vertexData.applyToMesh(cylinder, options.updatable);
  61224. return cylinder;
  61225. };
  61226. /**
  61227. * Creates a torus mesh
  61228. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61229. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61230. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61231. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61232. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61233. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61234. * @param name defines the name of the mesh
  61235. * @param options defines the options used to create the mesh
  61236. * @param scene defines the hosting scene
  61237. * @returns the torus mesh
  61238. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61239. */
  61240. MeshBuilder.CreateTorus = function (name, options, scene) {
  61241. var torus = new BABYLON.Mesh(name, scene);
  61242. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61243. torus._originalBuilderSideOrientation = options.sideOrientation;
  61244. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61245. vertexData.applyToMesh(torus, options.updatable);
  61246. return torus;
  61247. };
  61248. /**
  61249. * Creates a torus knot mesh
  61250. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61251. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61252. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61253. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61254. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61255. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61256. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61257. * @param name defines the name of the mesh
  61258. * @param options defines the options used to create the mesh
  61259. * @param scene defines the hosting scene
  61260. * @returns the torus knot mesh
  61261. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61262. */
  61263. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61264. var torusKnot = new BABYLON.Mesh(name, scene);
  61265. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61266. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61267. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61268. vertexData.applyToMesh(torusKnot, options.updatable);
  61269. return torusKnot;
  61270. };
  61271. /**
  61272. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61273. * * 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
  61274. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61275. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61276. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61277. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61278. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61279. * * 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
  61280. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61281. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61282. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61283. * @param name defines the name of the new line system
  61284. * @param options defines the options used to create the line system
  61285. * @param scene defines the hosting scene
  61286. * @returns a new line system mesh
  61287. */
  61288. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61289. var instance = options.instance;
  61290. var lines = options.lines;
  61291. var colors = options.colors;
  61292. if (instance) { // lines update
  61293. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61294. var vertexColor;
  61295. var lineColors;
  61296. if (colors) {
  61297. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61298. }
  61299. var i = 0;
  61300. var c = 0;
  61301. for (var l = 0; l < lines.length; l++) {
  61302. var points = lines[l];
  61303. for (var p = 0; p < points.length; p++) {
  61304. positions[i] = points[p].x;
  61305. positions[i + 1] = points[p].y;
  61306. positions[i + 2] = points[p].z;
  61307. if (colors && vertexColor) {
  61308. lineColors = colors[l];
  61309. vertexColor[c] = lineColors[p].r;
  61310. vertexColor[c + 1] = lineColors[p].g;
  61311. vertexColor[c + 2] = lineColors[p].b;
  61312. vertexColor[c + 3] = lineColors[p].a;
  61313. c += 4;
  61314. }
  61315. i += 3;
  61316. }
  61317. }
  61318. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61319. if (colors && vertexColor) {
  61320. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61321. }
  61322. return instance;
  61323. }
  61324. // line system creation
  61325. var useVertexColor = (colors) ? true : false;
  61326. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61327. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61328. vertexData.applyToMesh(lineSystem, options.updatable);
  61329. return lineSystem;
  61330. };
  61331. /**
  61332. * Creates a line mesh
  61333. * 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
  61334. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61335. * * The parameter `points` is an array successive Vector3
  61336. * * 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
  61337. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61338. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61339. * * When updating an instance, remember that only point positions can change, not the number of points
  61340. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61341. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61342. * @param name defines the name of the new line system
  61343. * @param options defines the options used to create the line system
  61344. * @param scene defines the hosting scene
  61345. * @returns a new line mesh
  61346. */
  61347. MeshBuilder.CreateLines = function (name, options, scene) {
  61348. if (scene === void 0) { scene = null; }
  61349. var colors = (options.colors) ? [options.colors] : null;
  61350. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61351. return lines;
  61352. };
  61353. /**
  61354. * Creates a dashed line mesh
  61355. * * 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
  61356. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61357. * * The parameter `points` is an array successive Vector3
  61358. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61359. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61360. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61361. * * 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
  61362. * * When updating an instance, remember that only point positions can change, not the number of points
  61363. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61364. * @param name defines the name of the mesh
  61365. * @param options defines the options used to create the mesh
  61366. * @param scene defines the hosting scene
  61367. * @returns the dashed line mesh
  61368. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61369. */
  61370. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61371. if (scene === void 0) { scene = null; }
  61372. var points = options.points;
  61373. var instance = options.instance;
  61374. var gapSize = options.gapSize || 1;
  61375. var dashSize = options.dashSize || 3;
  61376. if (instance) { // dashed lines update
  61377. var positionFunction = function (positions) {
  61378. var curvect = BABYLON.Vector3.Zero();
  61379. var nbSeg = positions.length / 6;
  61380. var lg = 0;
  61381. var nb = 0;
  61382. var shft = 0;
  61383. var dashshft = 0;
  61384. var curshft = 0;
  61385. var p = 0;
  61386. var i = 0;
  61387. var j = 0;
  61388. for (i = 0; i < points.length - 1; i++) {
  61389. points[i + 1].subtractToRef(points[i], curvect);
  61390. lg += curvect.length();
  61391. }
  61392. shft = lg / nbSeg;
  61393. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61394. for (i = 0; i < points.length - 1; i++) {
  61395. points[i + 1].subtractToRef(points[i], curvect);
  61396. nb = Math.floor(curvect.length() / shft);
  61397. curvect.normalize();
  61398. j = 0;
  61399. while (j < nb && p < positions.length) {
  61400. curshft = shft * j;
  61401. positions[p] = points[i].x + curshft * curvect.x;
  61402. positions[p + 1] = points[i].y + curshft * curvect.y;
  61403. positions[p + 2] = points[i].z + curshft * curvect.z;
  61404. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61405. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61406. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61407. p += 6;
  61408. j++;
  61409. }
  61410. }
  61411. while (p < positions.length) {
  61412. positions[p] = points[i].x;
  61413. positions[p + 1] = points[i].y;
  61414. positions[p + 2] = points[i].z;
  61415. p += 3;
  61416. }
  61417. };
  61418. instance.updateMeshPositions(positionFunction, false);
  61419. return instance;
  61420. }
  61421. // dashed lines creation
  61422. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61423. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61424. vertexData.applyToMesh(dashedLines, options.updatable);
  61425. dashedLines.dashSize = dashSize;
  61426. dashedLines.gapSize = gapSize;
  61427. return dashedLines;
  61428. };
  61429. /**
  61430. * 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.
  61431. * * 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.
  61432. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61433. * * 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.
  61434. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61435. * * 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
  61436. * * 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
  61437. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61438. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61439. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61440. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61441. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61442. * @param name defines the name of the mesh
  61443. * @param options defines the options used to create the mesh
  61444. * @param scene defines the hosting scene
  61445. * @returns the extruded shape mesh
  61446. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61447. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61448. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61449. */
  61450. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61451. if (scene === void 0) { scene = null; }
  61452. var path = options.path;
  61453. var shape = options.shape;
  61454. var scale = options.scale || 1;
  61455. var rotation = options.rotation || 0;
  61456. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61457. var updatable = options.updatable;
  61458. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61459. var instance = options.instance || null;
  61460. var invertUV = options.invertUV || false;
  61461. 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);
  61462. };
  61463. /**
  61464. * Creates an custom extruded shape mesh.
  61465. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61466. * * 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.
  61467. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61468. * * 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
  61469. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61470. * * 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
  61471. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61472. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61473. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61474. * * 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
  61475. * * 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
  61476. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61477. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61478. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61479. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61480. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61481. * @param name defines the name of the mesh
  61482. * @param options defines the options used to create the mesh
  61483. * @param scene defines the hosting scene
  61484. * @returns the custom extruded shape mesh
  61485. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61486. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61487. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61488. */
  61489. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61490. var path = options.path;
  61491. var shape = options.shape;
  61492. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61493. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61494. var ribbonCloseArray = options.ribbonCloseArray || false;
  61495. var ribbonClosePath = options.ribbonClosePath || false;
  61496. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61497. var updatable = options.updatable;
  61498. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61499. var instance = options.instance;
  61500. var invertUV = options.invertUV || false;
  61501. 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);
  61502. };
  61503. /**
  61504. * Creates lathe mesh.
  61505. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61506. * * 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
  61507. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61508. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61509. * * 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
  61510. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61511. * * 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
  61512. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61513. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61514. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61515. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61516. * @param name defines the name of the mesh
  61517. * @param options defines the options used to create the mesh
  61518. * @param scene defines the hosting scene
  61519. * @returns the lathe mesh
  61520. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61521. */
  61522. MeshBuilder.CreateLathe = function (name, options, scene) {
  61523. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61524. var closed = (options.closed === undefined) ? true : options.closed;
  61525. var shape = options.shape;
  61526. var radius = options.radius || 1;
  61527. var tessellation = options.tessellation || 64;
  61528. var updatable = options.updatable;
  61529. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61530. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61531. var pi2 = Math.PI * 2;
  61532. var paths = new Array();
  61533. var invertUV = options.invertUV || false;
  61534. var i = 0;
  61535. var p = 0;
  61536. var step = pi2 / tessellation * arc;
  61537. var rotated;
  61538. var path = new Array();
  61539. for (i = 0; i <= tessellation; i++) {
  61540. var path = [];
  61541. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61542. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61543. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61544. }
  61545. for (p = 0; p < shape.length; p++) {
  61546. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61547. path.push(rotated);
  61548. }
  61549. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61550. 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));
  61551. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61552. }
  61553. paths.push(path);
  61554. }
  61555. // lathe ribbon
  61556. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61557. return lathe;
  61558. };
  61559. /**
  61560. * Creates a plane mesh
  61561. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61562. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61563. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61564. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61565. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61566. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61567. * @param name defines the name of the mesh
  61568. * @param options defines the options used to create the mesh
  61569. * @param scene defines the hosting scene
  61570. * @returns the plane mesh
  61571. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61572. */
  61573. MeshBuilder.CreatePlane = function (name, options, scene) {
  61574. var plane = new BABYLON.Mesh(name, scene);
  61575. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61576. plane._originalBuilderSideOrientation = options.sideOrientation;
  61577. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61578. vertexData.applyToMesh(plane, options.updatable);
  61579. if (options.sourcePlane) {
  61580. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61581. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61582. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61583. plane.rotate(vectorProduct, product);
  61584. }
  61585. return plane;
  61586. };
  61587. /**
  61588. * Creates a ground mesh
  61589. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61590. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61591. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61592. * @param name defines the name of the mesh
  61593. * @param options defines the options used to create the mesh
  61594. * @param scene defines the hosting scene
  61595. * @returns the ground mesh
  61596. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61597. */
  61598. MeshBuilder.CreateGround = function (name, options, scene) {
  61599. var ground = new BABYLON.GroundMesh(name, scene);
  61600. ground._setReady(false);
  61601. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61602. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61603. ground._width = options.width || 1;
  61604. ground._height = options.height || 1;
  61605. ground._maxX = ground._width / 2;
  61606. ground._maxZ = ground._height / 2;
  61607. ground._minX = -ground._maxX;
  61608. ground._minZ = -ground._maxZ;
  61609. var vertexData = BABYLON.VertexData.CreateGround(options);
  61610. vertexData.applyToMesh(ground, options.updatable);
  61611. ground._setReady(true);
  61612. return ground;
  61613. };
  61614. /**
  61615. * Creates a tiled ground mesh
  61616. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61617. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61618. * * 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
  61619. * * 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
  61620. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61621. * @param name defines the name of the mesh
  61622. * @param options defines the options used to create the mesh
  61623. * @param scene defines the hosting scene
  61624. * @returns the tiled ground mesh
  61625. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61626. */
  61627. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61628. var tiledGround = new BABYLON.Mesh(name, scene);
  61629. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61630. vertexData.applyToMesh(tiledGround, options.updatable);
  61631. return tiledGround;
  61632. };
  61633. /**
  61634. * Creates a ground mesh from a height map
  61635. * * The parameter `url` sets the URL of the height map image resource.
  61636. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61637. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61638. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61639. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61640. * * 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.
  61641. * * 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).
  61642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61643. * @param name defines the name of the mesh
  61644. * @param url defines the url to the height map
  61645. * @param options defines the options used to create the mesh
  61646. * @param scene defines the hosting scene
  61647. * @returns the ground mesh
  61648. * @see http://doc.babylonjs.com/babylon101/height_map
  61649. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61650. */
  61651. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61652. var width = options.width || 10.0;
  61653. var height = options.height || 10.0;
  61654. var subdivisions = options.subdivisions || 1 | 0;
  61655. var minHeight = options.minHeight || 0.0;
  61656. var maxHeight = options.maxHeight || 1.0;
  61657. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61658. var updatable = options.updatable;
  61659. var onReady = options.onReady;
  61660. var ground = new BABYLON.GroundMesh(name, scene);
  61661. ground._subdivisionsX = subdivisions;
  61662. ground._subdivisionsY = subdivisions;
  61663. ground._width = width;
  61664. ground._height = height;
  61665. ground._maxX = ground._width / 2.0;
  61666. ground._maxZ = ground._height / 2.0;
  61667. ground._minX = -ground._maxX;
  61668. ground._minZ = -ground._maxZ;
  61669. ground._setReady(false);
  61670. var onload = function (img) {
  61671. // Getting height map data
  61672. var canvas = document.createElement("canvas");
  61673. var context = canvas.getContext("2d");
  61674. if (!context) {
  61675. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61676. }
  61677. if (scene.isDisposed) {
  61678. return;
  61679. }
  61680. var bufferWidth = img.width;
  61681. var bufferHeight = img.height;
  61682. canvas.width = bufferWidth;
  61683. canvas.height = bufferHeight;
  61684. context.drawImage(img, 0, 0);
  61685. // Create VertexData from map data
  61686. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61687. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61688. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61689. width: width, height: height,
  61690. subdivisions: subdivisions,
  61691. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61692. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61693. });
  61694. vertexData.applyToMesh(ground, updatable);
  61695. //execute ready callback, if set
  61696. if (onReady) {
  61697. onReady(ground);
  61698. }
  61699. ground._setReady(true);
  61700. };
  61701. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61702. return ground;
  61703. };
  61704. /**
  61705. * Creates a polygon mesh
  61706. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61707. * * 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
  61708. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61709. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61710. * * 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)
  61711. * * Remember you can only change the shape positions, not their number when updating a polygon
  61712. * @param name defines the name of the mesh
  61713. * @param options defines the options used to create the mesh
  61714. * @param scene defines the hosting scene
  61715. * @returns the polygon mesh
  61716. */
  61717. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61718. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61719. var shape = options.shape;
  61720. var holes = options.holes || [];
  61721. var depth = options.depth || 0;
  61722. var contours = [];
  61723. var hole = [];
  61724. for (var i = 0; i < shape.length; i++) {
  61725. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61726. }
  61727. var epsilon = 0.00000001;
  61728. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61729. contours.pop();
  61730. }
  61731. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61732. for (var hNb = 0; hNb < holes.length; hNb++) {
  61733. hole = [];
  61734. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61735. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61736. }
  61737. polygonTriangulation.addHole(hole);
  61738. }
  61739. var polygon = polygonTriangulation.build(options.updatable, depth);
  61740. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61741. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61742. vertexData.applyToMesh(polygon, options.updatable);
  61743. return polygon;
  61744. };
  61745. ;
  61746. /**
  61747. * Creates an extruded polygon mesh, with depth in the Y direction.
  61748. * * 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)
  61749. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61750. * @param name defines the name of the mesh
  61751. * @param options defines the options used to create the mesh
  61752. * @param scene defines the hosting scene
  61753. * @returns the polygon mesh
  61754. */
  61755. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61756. return MeshBuilder.CreatePolygon(name, options, scene);
  61757. };
  61758. ;
  61759. /**
  61760. * Creates a tube mesh.
  61761. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61762. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61763. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61764. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61765. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61766. * * 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)
  61767. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61768. * * 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
  61769. * * 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
  61770. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61771. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61772. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61773. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61774. * @param name defines the name of the mesh
  61775. * @param options defines the options used to create the mesh
  61776. * @param scene defines the hosting scene
  61777. * @returns the tube mesh
  61778. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61779. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61780. */
  61781. MeshBuilder.CreateTube = function (name, options, scene) {
  61782. var path = options.path;
  61783. var instance = options.instance;
  61784. var radius = 1.0;
  61785. if (instance) {
  61786. radius = instance.radius;
  61787. }
  61788. if (options.radius !== undefined) {
  61789. radius = options.radius;
  61790. }
  61791. ;
  61792. var tessellation = options.tessellation || 64 | 0;
  61793. var radiusFunction = options.radiusFunction || null;
  61794. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61795. var invertUV = options.invertUV || false;
  61796. var updatable = options.updatable;
  61797. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61798. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61799. // tube geometry
  61800. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61801. var tangents = path3D.getTangents();
  61802. var normals = path3D.getNormals();
  61803. var distances = path3D.getDistances();
  61804. var pi2 = Math.PI * 2;
  61805. var step = pi2 / tessellation * arc;
  61806. var returnRadius = function () { return radius; };
  61807. var radiusFunctionFinal = radiusFunction || returnRadius;
  61808. var circlePath;
  61809. var rad;
  61810. var normal;
  61811. var rotated;
  61812. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61813. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61814. for (var i = 0; i < path.length; i++) {
  61815. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61816. circlePath = Array(); // current circle array
  61817. normal = normals[i]; // current normal
  61818. for (var t = 0; t < tessellation; t++) {
  61819. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61820. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61821. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61822. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61823. circlePath[t] = rotated;
  61824. }
  61825. circlePaths[index] = circlePath;
  61826. index++;
  61827. }
  61828. // cap
  61829. var capPath = function (nbPoints, pathIndex) {
  61830. var pointCap = Array();
  61831. for (var i = 0; i < nbPoints; i++) {
  61832. pointCap.push(path[pathIndex]);
  61833. }
  61834. return pointCap;
  61835. };
  61836. switch (cap) {
  61837. case BABYLON.Mesh.NO_CAP:
  61838. break;
  61839. case BABYLON.Mesh.CAP_START:
  61840. circlePaths[0] = capPath(tessellation, 0);
  61841. circlePaths[1] = circlePaths[2].slice(0);
  61842. break;
  61843. case BABYLON.Mesh.CAP_END:
  61844. circlePaths[index] = circlePaths[index - 1].slice(0);
  61845. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61846. break;
  61847. case BABYLON.Mesh.CAP_ALL:
  61848. circlePaths[0] = capPath(tessellation, 0);
  61849. circlePaths[1] = circlePaths[2].slice(0);
  61850. circlePaths[index] = circlePaths[index - 1].slice(0);
  61851. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61852. break;
  61853. default:
  61854. break;
  61855. }
  61856. return circlePaths;
  61857. };
  61858. var path3D;
  61859. var pathArray;
  61860. if (instance) { // tube update
  61861. var arc = options.arc || instance.arc;
  61862. path3D = (instance.path3D).update(path);
  61863. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61864. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61865. instance.path3D = path3D;
  61866. instance.pathArray = pathArray;
  61867. instance.arc = arc;
  61868. instance.radius = radius;
  61869. return instance;
  61870. }
  61871. // tube creation
  61872. path3D = new BABYLON.Path3D(path);
  61873. var newPathArray = new Array();
  61874. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61875. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61876. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61877. tube.pathArray = pathArray;
  61878. tube.path3D = path3D;
  61879. tube.tessellation = tessellation;
  61880. tube.cap = cap;
  61881. tube.arc = options.arc;
  61882. tube.radius = radius;
  61883. return tube;
  61884. };
  61885. /**
  61886. * Creates a polyhedron mesh
  61887. * * 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
  61888. * * The parameter `size` (positive float, default 1) sets the polygon size
  61889. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61890. * * 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`
  61891. * * 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
  61892. * * 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)`)
  61893. * * 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
  61894. * * 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
  61895. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61896. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61897. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61898. * @param name defines the name of the mesh
  61899. * @param options defines the options used to create the mesh
  61900. * @param scene defines the hosting scene
  61901. * @returns the polyhedron mesh
  61902. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61903. */
  61904. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61905. var polyhedron = new BABYLON.Mesh(name, scene);
  61906. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61907. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61908. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61909. vertexData.applyToMesh(polyhedron, options.updatable);
  61910. return polyhedron;
  61911. };
  61912. /**
  61913. * Creates a decal mesh.
  61914. * 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
  61915. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61916. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61917. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61918. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61919. * @param name defines the name of the mesh
  61920. * @param sourceMesh defines the mesh where the decal must be applied
  61921. * @param options defines the options used to create the mesh
  61922. * @param scene defines the hosting scene
  61923. * @returns the decal mesh
  61924. * @see http://doc.babylonjs.com/how_to/decals
  61925. */
  61926. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61927. var indices = sourceMesh.getIndices();
  61928. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61929. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61930. var position = options.position || BABYLON.Vector3.Zero();
  61931. var normal = options.normal || BABYLON.Vector3.Up();
  61932. var size = options.size || BABYLON.Vector3.One();
  61933. var angle = options.angle || 0;
  61934. // Getting correct rotation
  61935. if (!normal) {
  61936. var target = new BABYLON.Vector3(0, 0, 1);
  61937. var camera = sourceMesh.getScene().activeCamera;
  61938. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61939. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61940. }
  61941. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61942. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61943. var pitch = Math.atan2(normal.y, len);
  61944. // Matrix
  61945. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61946. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61947. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61948. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61949. var vertexData = new BABYLON.VertexData();
  61950. vertexData.indices = [];
  61951. vertexData.positions = [];
  61952. vertexData.normals = [];
  61953. vertexData.uvs = [];
  61954. var currentVertexDataIndex = 0;
  61955. var extractDecalVector3 = function (indexId) {
  61956. var result = new BABYLON.PositionNormalVertex();
  61957. if (!indices || !positions || !normals) {
  61958. return result;
  61959. }
  61960. var vertexId = indices[indexId];
  61961. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61962. // Send vector to decal local world
  61963. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61964. // Get normal
  61965. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61966. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61967. return result;
  61968. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61969. var clip = function (vertices, axis) {
  61970. if (vertices.length === 0) {
  61971. return vertices;
  61972. }
  61973. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61974. var clipVertices = function (v0, v1) {
  61975. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61976. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61977. };
  61978. var result = new Array();
  61979. for (var index = 0; index < vertices.length; index += 3) {
  61980. var v1Out;
  61981. var v2Out;
  61982. var v3Out;
  61983. var total = 0;
  61984. var nV1 = null;
  61985. var nV2 = null;
  61986. var nV3 = null;
  61987. var nV4 = null;
  61988. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61989. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61990. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61991. v1Out = d1 > 0;
  61992. v2Out = d2 > 0;
  61993. v3Out = d3 > 0;
  61994. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61995. switch (total) {
  61996. case 0:
  61997. result.push(vertices[index]);
  61998. result.push(vertices[index + 1]);
  61999. result.push(vertices[index + 2]);
  62000. break;
  62001. case 1:
  62002. if (v1Out) {
  62003. nV1 = vertices[index + 1];
  62004. nV2 = vertices[index + 2];
  62005. nV3 = clipVertices(vertices[index], nV1);
  62006. nV4 = clipVertices(vertices[index], nV2);
  62007. }
  62008. if (v2Out) {
  62009. nV1 = vertices[index];
  62010. nV2 = vertices[index + 2];
  62011. nV3 = clipVertices(vertices[index + 1], nV1);
  62012. nV4 = clipVertices(vertices[index + 1], nV2);
  62013. result.push(nV3);
  62014. result.push(nV2.clone());
  62015. result.push(nV1.clone());
  62016. result.push(nV2.clone());
  62017. result.push(nV3.clone());
  62018. result.push(nV4);
  62019. break;
  62020. }
  62021. if (v3Out) {
  62022. nV1 = vertices[index];
  62023. nV2 = vertices[index + 1];
  62024. nV3 = clipVertices(vertices[index + 2], nV1);
  62025. nV4 = clipVertices(vertices[index + 2], nV2);
  62026. }
  62027. if (nV1 && nV2 && nV3 && nV4) {
  62028. result.push(nV1.clone());
  62029. result.push(nV2.clone());
  62030. result.push(nV3);
  62031. result.push(nV4);
  62032. result.push(nV3.clone());
  62033. result.push(nV2.clone());
  62034. }
  62035. break;
  62036. case 2:
  62037. if (!v1Out) {
  62038. nV1 = vertices[index].clone();
  62039. nV2 = clipVertices(nV1, vertices[index + 1]);
  62040. nV3 = clipVertices(nV1, vertices[index + 2]);
  62041. result.push(nV1);
  62042. result.push(nV2);
  62043. result.push(nV3);
  62044. }
  62045. if (!v2Out) {
  62046. nV1 = vertices[index + 1].clone();
  62047. nV2 = clipVertices(nV1, vertices[index + 2]);
  62048. nV3 = clipVertices(nV1, vertices[index]);
  62049. result.push(nV1);
  62050. result.push(nV2);
  62051. result.push(nV3);
  62052. }
  62053. if (!v3Out) {
  62054. nV1 = vertices[index + 2].clone();
  62055. nV2 = clipVertices(nV1, vertices[index]);
  62056. nV3 = clipVertices(nV1, vertices[index + 1]);
  62057. result.push(nV1);
  62058. result.push(nV2);
  62059. result.push(nV3);
  62060. }
  62061. break;
  62062. case 3:
  62063. break;
  62064. }
  62065. }
  62066. return result;
  62067. };
  62068. for (var index = 0; index < indices.length; index += 3) {
  62069. var faceVertices = new Array();
  62070. faceVertices.push(extractDecalVector3(index));
  62071. faceVertices.push(extractDecalVector3(index + 1));
  62072. faceVertices.push(extractDecalVector3(index + 2));
  62073. // Clip
  62074. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  62075. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  62076. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  62077. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  62078. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  62079. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  62080. if (faceVertices.length === 0) {
  62081. continue;
  62082. }
  62083. // Add UVs and get back to world
  62084. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  62085. var vertex = faceVertices[vIndex];
  62086. //TODO check for Int32Array | Uint32Array | Uint16Array
  62087. vertexData.indices.push(currentVertexDataIndex);
  62088. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  62089. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  62090. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  62091. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  62092. currentVertexDataIndex++;
  62093. }
  62094. }
  62095. // Return mesh
  62096. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  62097. vertexData.applyToMesh(decal);
  62098. decal.position = position.clone();
  62099. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  62100. return decal;
  62101. };
  62102. // Privates
  62103. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  62104. // extrusion geometry
  62105. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  62106. var tangents = path3D.getTangents();
  62107. var normals = path3D.getNormals();
  62108. var binormals = path3D.getBinormals();
  62109. var distances = path3D.getDistances();
  62110. var angle = 0;
  62111. var returnScale = function () { return scale !== null ? scale : 1; };
  62112. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  62113. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  62114. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  62115. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  62116. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  62117. for (var i = 0; i < curve.length; i++) {
  62118. var shapePath = new Array();
  62119. var angleStep = rotate(i, distances[i]);
  62120. var scaleRatio = scl(i, distances[i]);
  62121. for (var p = 0; p < shape.length; p++) {
  62122. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  62123. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  62124. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  62125. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  62126. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  62127. shapePath[p] = rotated;
  62128. }
  62129. shapePaths[index] = shapePath;
  62130. angle += angleStep;
  62131. index++;
  62132. }
  62133. // cap
  62134. var capPath = function (shapePath) {
  62135. var pointCap = Array();
  62136. var barycenter = BABYLON.Vector3.Zero();
  62137. var i;
  62138. for (i = 0; i < shapePath.length; i++) {
  62139. barycenter.addInPlace(shapePath[i]);
  62140. }
  62141. barycenter.scaleInPlace(1.0 / shapePath.length);
  62142. for (i = 0; i < shapePath.length; i++) {
  62143. pointCap.push(barycenter);
  62144. }
  62145. return pointCap;
  62146. };
  62147. switch (cap) {
  62148. case BABYLON.Mesh.NO_CAP:
  62149. break;
  62150. case BABYLON.Mesh.CAP_START:
  62151. shapePaths[0] = capPath(shapePaths[2]);
  62152. shapePaths[1] = shapePaths[2];
  62153. break;
  62154. case BABYLON.Mesh.CAP_END:
  62155. shapePaths[index] = shapePaths[index - 1];
  62156. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62157. break;
  62158. case BABYLON.Mesh.CAP_ALL:
  62159. shapePaths[0] = capPath(shapePaths[2]);
  62160. shapePaths[1] = shapePaths[2];
  62161. shapePaths[index] = shapePaths[index - 1];
  62162. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  62163. break;
  62164. default:
  62165. break;
  62166. }
  62167. return shapePaths;
  62168. };
  62169. var path3D;
  62170. var pathArray;
  62171. if (instance) { // instance update
  62172. path3D = (instance.path3D).update(curve);
  62173. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62174. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62175. return instance;
  62176. }
  62177. // extruded shape creation
  62178. path3D = new BABYLON.Path3D(curve);
  62179. var newShapePaths = new Array();
  62180. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62181. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62182. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62183. extrudedGeneric.pathArray = pathArray;
  62184. extrudedGeneric.path3D = path3D;
  62185. extrudedGeneric.cap = cap;
  62186. return extrudedGeneric;
  62187. };
  62188. return MeshBuilder;
  62189. }());
  62190. BABYLON.MeshBuilder = MeshBuilder;
  62191. })(BABYLON || (BABYLON = {}));
  62192. //# sourceMappingURL=babylon.meshBuilder.js.map
  62193. var BABYLON;
  62194. (function (BABYLON) {
  62195. /**
  62196. * Draco compression (https://google.github.io/draco/)
  62197. *
  62198. * This class wraps the Draco module.
  62199. *
  62200. * **Encoder**
  62201. *
  62202. * The encoder is not currently implemented.
  62203. *
  62204. * **Decoder**
  62205. *
  62206. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62207. *
  62208. * To update the configuration, use the following code:
  62209. * ```javascript
  62210. * BABYLON.DracoCompression.Configuration = {
  62211. * decoder: {
  62212. * wasmUrl: "<url to the WebAssembly library>",
  62213. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62214. * fallbackUrl: "<url to the fallback JavaScript library>",
  62215. * }
  62216. * };
  62217. * ```
  62218. *
  62219. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62220. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62221. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62222. *
  62223. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62224. * ```javascript
  62225. * var dracoCompression = new BABYLON.DracoCompression();
  62226. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62227. * [BABYLON.VertexBuffer.PositionKind]: 0
  62228. * });
  62229. * ```
  62230. *
  62231. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62232. */
  62233. var DracoCompression = /** @class */ (function () {
  62234. /**
  62235. * Constructor
  62236. */
  62237. function DracoCompression() {
  62238. }
  62239. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62240. /**
  62241. * Returns true if the decoder is available.
  62242. */
  62243. get: function () {
  62244. if (typeof DracoDecoderModule !== "undefined") {
  62245. return true;
  62246. }
  62247. var decoder = DracoCompression.Configuration.decoder;
  62248. if (decoder) {
  62249. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62250. return true;
  62251. }
  62252. if (decoder.fallbackUrl) {
  62253. return true;
  62254. }
  62255. }
  62256. return false;
  62257. },
  62258. enumerable: true,
  62259. configurable: true
  62260. });
  62261. /**
  62262. * Stop all async operations and release resources.
  62263. */
  62264. DracoCompression.prototype.dispose = function () {
  62265. };
  62266. /**
  62267. * Decode Draco compressed mesh data to vertex data.
  62268. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62269. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62270. * @returns A promise that resolves with the decoded vertex data
  62271. */
  62272. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62273. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62274. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62275. var module = wrappedModule.module;
  62276. var vertexData = new BABYLON.VertexData();
  62277. var buffer = new module.DecoderBuffer();
  62278. buffer.Init(dataView, dataView.byteLength);
  62279. var decoder = new module.Decoder();
  62280. var geometry;
  62281. var status;
  62282. try {
  62283. var type = decoder.GetEncodedGeometryType(buffer);
  62284. switch (type) {
  62285. case module.TRIANGULAR_MESH:
  62286. geometry = new module.Mesh();
  62287. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62288. break;
  62289. case module.POINT_CLOUD:
  62290. geometry = new module.PointCloud();
  62291. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62292. break;
  62293. default:
  62294. throw new Error("Invalid geometry type " + type);
  62295. }
  62296. if (!status.ok() || !geometry.ptr) {
  62297. throw new Error(status.error_msg());
  62298. }
  62299. var numPoints = geometry.num_points();
  62300. if (type === module.TRIANGULAR_MESH) {
  62301. var numFaces = geometry.num_faces();
  62302. var faceIndices = new module.DracoInt32Array();
  62303. try {
  62304. var indices = new Uint32Array(numFaces * 3);
  62305. for (var i = 0; i < numFaces; i++) {
  62306. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62307. var offset = i * 3;
  62308. indices[offset + 0] = faceIndices.GetValue(0);
  62309. indices[offset + 1] = faceIndices.GetValue(1);
  62310. indices[offset + 2] = faceIndices.GetValue(2);
  62311. }
  62312. vertexData.indices = indices;
  62313. }
  62314. finally {
  62315. module.destroy(faceIndices);
  62316. }
  62317. }
  62318. for (var kind in attributes) {
  62319. var uniqueId = attributes[kind];
  62320. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62321. var dracoData = new module.DracoFloat32Array();
  62322. try {
  62323. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62324. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62325. for (var i = 0; i < babylonData.length; i++) {
  62326. babylonData[i] = dracoData.GetValue(i);
  62327. }
  62328. vertexData.set(babylonData, kind);
  62329. }
  62330. finally {
  62331. module.destroy(dracoData);
  62332. }
  62333. }
  62334. }
  62335. finally {
  62336. if (geometry) {
  62337. module.destroy(geometry);
  62338. }
  62339. module.destroy(decoder);
  62340. module.destroy(buffer);
  62341. }
  62342. return vertexData;
  62343. });
  62344. };
  62345. DracoCompression._GetDecoderModule = function () {
  62346. if (!DracoCompression._DecoderModulePromise) {
  62347. var promise = null;
  62348. var config_1 = {};
  62349. if (typeof DracoDecoderModule !== "undefined") {
  62350. promise = Promise.resolve();
  62351. }
  62352. else {
  62353. var decoder = DracoCompression.Configuration.decoder;
  62354. if (decoder) {
  62355. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62356. promise = Promise.all([
  62357. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62358. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62359. config_1.wasmBinary = data;
  62360. })
  62361. ]);
  62362. }
  62363. else if (decoder.fallbackUrl) {
  62364. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62365. }
  62366. }
  62367. }
  62368. if (!promise) {
  62369. throw new Error("Draco decoder module is not available");
  62370. }
  62371. DracoCompression._DecoderModulePromise = promise.then(function () {
  62372. return new Promise(function (resolve) {
  62373. config_1.onModuleLoaded = function (decoderModule) {
  62374. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62375. resolve({ module: decoderModule });
  62376. };
  62377. DracoDecoderModule(config_1);
  62378. });
  62379. });
  62380. }
  62381. return DracoCompression._DecoderModulePromise;
  62382. };
  62383. DracoCompression._LoadScriptAsync = function (url) {
  62384. return new Promise(function (resolve, reject) {
  62385. BABYLON.Tools.LoadScript(url, function () {
  62386. resolve();
  62387. }, function (message) {
  62388. reject(new Error(message));
  62389. });
  62390. });
  62391. };
  62392. DracoCompression._LoadFileAsync = function (url) {
  62393. return new Promise(function (resolve, reject) {
  62394. BABYLON.Tools.LoadFile(url, function (data) {
  62395. resolve(data);
  62396. }, undefined, undefined, true, function (request, exception) {
  62397. reject(exception);
  62398. });
  62399. });
  62400. };
  62401. /**
  62402. * The configuration. Defaults to the following urls:
  62403. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62404. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62405. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62406. */
  62407. DracoCompression.Configuration = {
  62408. decoder: {
  62409. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62410. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62411. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62412. }
  62413. };
  62414. return DracoCompression;
  62415. }());
  62416. BABYLON.DracoCompression = DracoCompression;
  62417. })(BABYLON || (BABYLON = {}));
  62418. //# sourceMappingURL=babylon.dracoCompression.js.map
  62419. var BABYLON;
  62420. (function (BABYLON) {
  62421. var AudioEngine = /** @class */ (function () {
  62422. function AudioEngine() {
  62423. this._audioContext = null;
  62424. this._audioContextInitialized = false;
  62425. this.canUseWebAudio = false;
  62426. this.WarnedWebAudioUnsupported = false;
  62427. this.unlocked = false;
  62428. this.isMP3supported = false;
  62429. this.isOGGsupported = false;
  62430. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62431. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62432. this.canUseWebAudio = true;
  62433. }
  62434. var audioElem = document.createElement('audio');
  62435. try {
  62436. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62437. this.isMP3supported = true;
  62438. }
  62439. }
  62440. catch (e) {
  62441. // protect error during capability check.
  62442. }
  62443. try {
  62444. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62445. this.isOGGsupported = true;
  62446. }
  62447. }
  62448. catch (e) {
  62449. // protect error during capability check.
  62450. }
  62451. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62452. this._unlockiOSaudio();
  62453. }
  62454. else {
  62455. this.unlocked = true;
  62456. }
  62457. }
  62458. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62459. get: function () {
  62460. if (!this._audioContextInitialized) {
  62461. this._initializeAudioContext();
  62462. }
  62463. return this._audioContext;
  62464. },
  62465. enumerable: true,
  62466. configurable: true
  62467. });
  62468. AudioEngine.prototype._unlockiOSaudio = function () {
  62469. var _this = this;
  62470. var unlockaudio = function () {
  62471. if (!_this.audioContext) {
  62472. return;
  62473. }
  62474. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62475. var source = _this.audioContext.createBufferSource();
  62476. source.buffer = buffer;
  62477. source.connect(_this.audioContext.destination);
  62478. source.start(0);
  62479. setTimeout(function () {
  62480. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62481. _this.unlocked = true;
  62482. window.removeEventListener('touchend', unlockaudio, false);
  62483. if (_this.onAudioUnlocked) {
  62484. _this.onAudioUnlocked();
  62485. }
  62486. }
  62487. }, 0);
  62488. };
  62489. window.addEventListener('touchend', unlockaudio, false);
  62490. };
  62491. AudioEngine.prototype._initializeAudioContext = function () {
  62492. try {
  62493. if (this.canUseWebAudio) {
  62494. this._audioContext = new AudioContext();
  62495. // create a global volume gain node
  62496. this.masterGain = this._audioContext.createGain();
  62497. this.masterGain.gain.value = 1;
  62498. this.masterGain.connect(this._audioContext.destination);
  62499. this._audioContextInitialized = true;
  62500. }
  62501. }
  62502. catch (e) {
  62503. this.canUseWebAudio = false;
  62504. BABYLON.Tools.Error("Web Audio: " + e.message);
  62505. }
  62506. };
  62507. AudioEngine.prototype.dispose = function () {
  62508. if (this.canUseWebAudio && this._audioContextInitialized) {
  62509. if (this._connectedAnalyser && this._audioContext) {
  62510. this._connectedAnalyser.stopDebugCanvas();
  62511. this._connectedAnalyser.dispose();
  62512. this.masterGain.disconnect();
  62513. this.masterGain.connect(this._audioContext.destination);
  62514. this._connectedAnalyser = null;
  62515. }
  62516. this.masterGain.gain.value = 1;
  62517. }
  62518. this.WarnedWebAudioUnsupported = false;
  62519. };
  62520. AudioEngine.prototype.getGlobalVolume = function () {
  62521. if (this.canUseWebAudio && this._audioContextInitialized) {
  62522. return this.masterGain.gain.value;
  62523. }
  62524. else {
  62525. return -1;
  62526. }
  62527. };
  62528. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62529. if (this.canUseWebAudio && this._audioContextInitialized) {
  62530. this.masterGain.gain.value = newVolume;
  62531. }
  62532. };
  62533. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62534. if (this._connectedAnalyser) {
  62535. this._connectedAnalyser.stopDebugCanvas();
  62536. }
  62537. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62538. this._connectedAnalyser = analyser;
  62539. this.masterGain.disconnect();
  62540. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62541. }
  62542. };
  62543. return AudioEngine;
  62544. }());
  62545. BABYLON.AudioEngine = AudioEngine;
  62546. })(BABYLON || (BABYLON = {}));
  62547. //# sourceMappingURL=babylon.audioEngine.js.map
  62548. var BABYLON;
  62549. (function (BABYLON) {
  62550. var Sound = /** @class */ (function () {
  62551. /**
  62552. * Create a sound and attach it to a scene
  62553. * @param name Name of your sound
  62554. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62555. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62556. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62557. */
  62558. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62559. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62560. var _this = this;
  62561. this.autoplay = false;
  62562. this.loop = false;
  62563. this.useCustomAttenuation = false;
  62564. this.spatialSound = false;
  62565. this.refDistance = 1;
  62566. this.rolloffFactor = 1;
  62567. this.maxDistance = 100;
  62568. this.distanceModel = "linear";
  62569. this._panningModel = "equalpower";
  62570. this._playbackRate = 1;
  62571. this._streaming = false;
  62572. this._startTime = 0;
  62573. this._startOffset = 0;
  62574. this._position = BABYLON.Vector3.Zero();
  62575. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62576. this._volume = 1;
  62577. this._isReadyToPlay = false;
  62578. this.isPlaying = false;
  62579. this.isPaused = false;
  62580. this._isDirectional = false;
  62581. // Used if you'd like to create a directional sound.
  62582. // If not set, the sound will be omnidirectional
  62583. this._coneInnerAngle = 360;
  62584. this._coneOuterAngle = 360;
  62585. this._coneOuterGain = 0;
  62586. this._isOutputConnected = false;
  62587. this._urlType = "Unknown";
  62588. this.name = name;
  62589. this._scene = scene;
  62590. this._readyToPlayCallback = readyToPlayCallback;
  62591. // Default custom attenuation function is a linear attenuation
  62592. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62593. if (currentDistance < maxDistance) {
  62594. return currentVolume * (1 - currentDistance / maxDistance);
  62595. }
  62596. else {
  62597. return 0;
  62598. }
  62599. };
  62600. if (options) {
  62601. this.autoplay = options.autoplay || false;
  62602. this.loop = options.loop || false;
  62603. // if volume === 0, we need another way to check this option
  62604. if (options.volume !== undefined) {
  62605. this._volume = options.volume;
  62606. }
  62607. this.spatialSound = options.spatialSound || false;
  62608. this.maxDistance = options.maxDistance || 100;
  62609. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62610. this.rolloffFactor = options.rolloffFactor || 1;
  62611. this.refDistance = options.refDistance || 1;
  62612. this.distanceModel = options.distanceModel || "linear";
  62613. this._playbackRate = options.playbackRate || 1;
  62614. this._streaming = options.streaming || false;
  62615. }
  62616. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62617. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62618. this._soundGain.gain.value = this._volume;
  62619. this._inputAudioNode = this._soundGain;
  62620. this._ouputAudioNode = this._soundGain;
  62621. if (this.spatialSound) {
  62622. this._createSpatialParameters();
  62623. }
  62624. this._scene.mainSoundTrack.AddSound(this);
  62625. var validParameter = true;
  62626. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62627. if (urlOrArrayBuffer) {
  62628. try {
  62629. if (typeof (urlOrArrayBuffer) === "string") {
  62630. this._urlType = "String";
  62631. }
  62632. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62633. this._urlType = "ArrayBuffer";
  62634. }
  62635. else if (urlOrArrayBuffer instanceof MediaStream) {
  62636. this._urlType = "MediaStream";
  62637. }
  62638. else if (Array.isArray(urlOrArrayBuffer)) {
  62639. this._urlType = "Array";
  62640. }
  62641. var urls = [];
  62642. var codecSupportedFound = false;
  62643. switch (this._urlType) {
  62644. case "MediaStream":
  62645. this._streaming = true;
  62646. this._isReadyToPlay = true;
  62647. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62648. if (this.autoplay) {
  62649. this.play();
  62650. }
  62651. if (this._readyToPlayCallback) {
  62652. this._readyToPlayCallback();
  62653. }
  62654. break;
  62655. case "ArrayBuffer":
  62656. if (urlOrArrayBuffer.byteLength > 0) {
  62657. codecSupportedFound = true;
  62658. this._soundLoaded(urlOrArrayBuffer);
  62659. }
  62660. break;
  62661. case "String":
  62662. urls.push(urlOrArrayBuffer);
  62663. case "Array":
  62664. if (urls.length === 0)
  62665. urls = urlOrArrayBuffer;
  62666. // If we found a supported format, we load it immediately and stop the loop
  62667. for (var i = 0; i < urls.length; i++) {
  62668. var url = urls[i];
  62669. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62670. codecSupportedFound = true;
  62671. }
  62672. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62673. codecSupportedFound = true;
  62674. }
  62675. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62676. codecSupportedFound = true;
  62677. }
  62678. if (url.indexOf("blob:") !== -1) {
  62679. codecSupportedFound = true;
  62680. }
  62681. if (codecSupportedFound) {
  62682. // Loading sound using XHR2
  62683. if (!this._streaming) {
  62684. this._scene._loadFile(url, function (data) {
  62685. _this._soundLoaded(data);
  62686. }, undefined, true, true, function (exception) {
  62687. if (exception) {
  62688. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62689. }
  62690. BABYLON.Tools.Error("Sound creation aborted.");
  62691. _this._scene.mainSoundTrack.RemoveSound(_this);
  62692. });
  62693. }
  62694. // Streaming sound using HTML5 Audio tag
  62695. else {
  62696. this._htmlAudioElement = new Audio(url);
  62697. this._htmlAudioElement.controls = false;
  62698. this._htmlAudioElement.loop = this.loop;
  62699. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62700. this._htmlAudioElement.preload = "auto";
  62701. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62702. _this._isReadyToPlay = true;
  62703. if (_this.autoplay) {
  62704. _this.play();
  62705. }
  62706. if (_this._readyToPlayCallback) {
  62707. _this._readyToPlayCallback();
  62708. }
  62709. });
  62710. document.body.appendChild(this._htmlAudioElement);
  62711. }
  62712. break;
  62713. }
  62714. }
  62715. break;
  62716. default:
  62717. validParameter = false;
  62718. break;
  62719. }
  62720. if (!validParameter) {
  62721. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62722. }
  62723. else {
  62724. if (!codecSupportedFound) {
  62725. this._isReadyToPlay = true;
  62726. // Simulating a ready to play event to avoid breaking code path
  62727. if (this._readyToPlayCallback) {
  62728. window.setTimeout(function () {
  62729. if (_this._readyToPlayCallback) {
  62730. _this._readyToPlayCallback();
  62731. }
  62732. }, 1000);
  62733. }
  62734. }
  62735. }
  62736. }
  62737. catch (ex) {
  62738. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62739. this._scene.mainSoundTrack.RemoveSound(this);
  62740. }
  62741. }
  62742. }
  62743. else {
  62744. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62745. this._scene.mainSoundTrack.AddSound(this);
  62746. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62747. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62748. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62749. }
  62750. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62751. if (this._readyToPlayCallback) {
  62752. window.setTimeout(function () {
  62753. if (_this._readyToPlayCallback) {
  62754. _this._readyToPlayCallback();
  62755. }
  62756. }, 1000);
  62757. }
  62758. }
  62759. }
  62760. Sound.prototype.dispose = function () {
  62761. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62762. if (this.isPlaying) {
  62763. this.stop();
  62764. }
  62765. this._isReadyToPlay = false;
  62766. if (this.soundTrackId === -1) {
  62767. this._scene.mainSoundTrack.RemoveSound(this);
  62768. }
  62769. else {
  62770. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62771. }
  62772. if (this._soundGain) {
  62773. this._soundGain.disconnect();
  62774. this._soundGain = null;
  62775. }
  62776. if (this._soundPanner) {
  62777. this._soundPanner.disconnect();
  62778. this._soundPanner = null;
  62779. }
  62780. if (this._soundSource) {
  62781. this._soundSource.disconnect();
  62782. this._soundSource = null;
  62783. }
  62784. this._audioBuffer = null;
  62785. if (this._htmlAudioElement) {
  62786. this._htmlAudioElement.pause();
  62787. this._htmlAudioElement.src = "";
  62788. document.body.removeChild(this._htmlAudioElement);
  62789. }
  62790. if (this._streamingSource) {
  62791. this._streamingSource.disconnect();
  62792. }
  62793. if (this._connectedMesh && this._registerFunc) {
  62794. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62795. this._connectedMesh = null;
  62796. }
  62797. }
  62798. };
  62799. Sound.prototype.isReady = function () {
  62800. return this._isReadyToPlay;
  62801. };
  62802. Sound.prototype._soundLoaded = function (audioData) {
  62803. var _this = this;
  62804. if (!BABYLON.Engine.audioEngine.audioContext) {
  62805. return;
  62806. }
  62807. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62808. _this._audioBuffer = buffer;
  62809. _this._isReadyToPlay = true;
  62810. if (_this.autoplay) {
  62811. _this.play();
  62812. }
  62813. if (_this._readyToPlayCallback) {
  62814. _this._readyToPlayCallback();
  62815. }
  62816. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62817. };
  62818. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62819. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62820. this._audioBuffer = audioBuffer;
  62821. this._isReadyToPlay = true;
  62822. }
  62823. };
  62824. Sound.prototype.updateOptions = function (options) {
  62825. if (options) {
  62826. this.loop = options.loop || this.loop;
  62827. this.maxDistance = options.maxDistance || this.maxDistance;
  62828. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62829. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62830. this.refDistance = options.refDistance || this.refDistance;
  62831. this.distanceModel = options.distanceModel || this.distanceModel;
  62832. this._playbackRate = options.playbackRate || this._playbackRate;
  62833. this._updateSpatialParameters();
  62834. if (this.isPlaying) {
  62835. if (this._streaming && this._htmlAudioElement) {
  62836. this._htmlAudioElement.playbackRate = this._playbackRate;
  62837. }
  62838. else {
  62839. if (this._soundSource) {
  62840. this._soundSource.playbackRate.value = this._playbackRate;
  62841. }
  62842. }
  62843. }
  62844. }
  62845. };
  62846. Sound.prototype._createSpatialParameters = function () {
  62847. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62848. if (this._scene.headphone) {
  62849. this._panningModel = "HRTF";
  62850. }
  62851. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62852. this._updateSpatialParameters();
  62853. this._soundPanner.connect(this._ouputAudioNode);
  62854. this._inputAudioNode = this._soundPanner;
  62855. }
  62856. };
  62857. Sound.prototype._updateSpatialParameters = function () {
  62858. if (this.spatialSound && this._soundPanner) {
  62859. if (this.useCustomAttenuation) {
  62860. // Tricks to disable in a way embedded Web Audio attenuation
  62861. this._soundPanner.distanceModel = "linear";
  62862. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62863. this._soundPanner.refDistance = 1;
  62864. this._soundPanner.rolloffFactor = 1;
  62865. this._soundPanner.panningModel = this._panningModel;
  62866. }
  62867. else {
  62868. this._soundPanner.distanceModel = this.distanceModel;
  62869. this._soundPanner.maxDistance = this.maxDistance;
  62870. this._soundPanner.refDistance = this.refDistance;
  62871. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62872. this._soundPanner.panningModel = this._panningModel;
  62873. }
  62874. }
  62875. };
  62876. Sound.prototype.switchPanningModelToHRTF = function () {
  62877. this._panningModel = "HRTF";
  62878. this._switchPanningModel();
  62879. };
  62880. Sound.prototype.switchPanningModelToEqualPower = function () {
  62881. this._panningModel = "equalpower";
  62882. this._switchPanningModel();
  62883. };
  62884. Sound.prototype._switchPanningModel = function () {
  62885. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62886. this._soundPanner.panningModel = this._panningModel;
  62887. }
  62888. };
  62889. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62890. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62891. if (this._isOutputConnected) {
  62892. this._ouputAudioNode.disconnect();
  62893. }
  62894. this._ouputAudioNode.connect(soundTrackAudioNode);
  62895. this._isOutputConnected = true;
  62896. }
  62897. };
  62898. /**
  62899. * Transform this sound into a directional source
  62900. * @param coneInnerAngle Size of the inner cone in degree
  62901. * @param coneOuterAngle Size of the outer cone in degree
  62902. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62903. */
  62904. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62905. if (coneOuterAngle < coneInnerAngle) {
  62906. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62907. return;
  62908. }
  62909. this._coneInnerAngle = coneInnerAngle;
  62910. this._coneOuterAngle = coneOuterAngle;
  62911. this._coneOuterGain = coneOuterGain;
  62912. this._isDirectional = true;
  62913. if (this.isPlaying && this.loop) {
  62914. this.stop();
  62915. this.play();
  62916. }
  62917. };
  62918. Sound.prototype.setPosition = function (newPosition) {
  62919. this._position = newPosition;
  62920. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62921. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62922. }
  62923. };
  62924. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62925. this._localDirection = newLocalDirection;
  62926. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62927. this._updateDirection();
  62928. }
  62929. };
  62930. Sound.prototype._updateDirection = function () {
  62931. if (!this._connectedMesh || !this._soundPanner) {
  62932. return;
  62933. }
  62934. var mat = this._connectedMesh.getWorldMatrix();
  62935. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62936. direction.normalize();
  62937. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62938. };
  62939. Sound.prototype.updateDistanceFromListener = function () {
  62940. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62941. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62942. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62943. }
  62944. };
  62945. Sound.prototype.setAttenuationFunction = function (callback) {
  62946. this._customAttenuationFunction = callback;
  62947. };
  62948. /**
  62949. * Play the sound
  62950. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62951. * @param offset (optional) Start the sound setting it at a specific time
  62952. */
  62953. Sound.prototype.play = function (time, offset) {
  62954. var _this = this;
  62955. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62956. try {
  62957. if (this._startOffset < 0) {
  62958. time = -this._startOffset;
  62959. this._startOffset = 0;
  62960. }
  62961. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62962. if (!this._soundSource || !this._streamingSource) {
  62963. if (this.spatialSound && this._soundPanner) {
  62964. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62965. if (this._isDirectional) {
  62966. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62967. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62968. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62969. if (this._connectedMesh) {
  62970. this._updateDirection();
  62971. }
  62972. else {
  62973. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62974. }
  62975. }
  62976. }
  62977. }
  62978. if (this._streaming) {
  62979. if (!this._streamingSource) {
  62980. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62981. this._htmlAudioElement.onended = function () { _this._onended(); };
  62982. this._htmlAudioElement.playbackRate = this._playbackRate;
  62983. }
  62984. this._streamingSource.disconnect();
  62985. this._streamingSource.connect(this._inputAudioNode);
  62986. if (this._htmlAudioElement) {
  62987. this._htmlAudioElement.play();
  62988. }
  62989. }
  62990. else {
  62991. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62992. this._soundSource.buffer = this._audioBuffer;
  62993. this._soundSource.connect(this._inputAudioNode);
  62994. this._soundSource.loop = this.loop;
  62995. this._soundSource.playbackRate.value = this._playbackRate;
  62996. this._soundSource.onended = function () { _this._onended(); };
  62997. if (this._soundSource.buffer) {
  62998. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62999. }
  63000. }
  63001. this._startTime = startTime;
  63002. this.isPlaying = true;
  63003. this.isPaused = false;
  63004. }
  63005. catch (ex) {
  63006. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  63007. }
  63008. }
  63009. };
  63010. Sound.prototype._onended = function () {
  63011. this.isPlaying = false;
  63012. if (this.onended) {
  63013. this.onended();
  63014. }
  63015. };
  63016. /**
  63017. * Stop the sound
  63018. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  63019. */
  63020. Sound.prototype.stop = function (time) {
  63021. if (this.isPlaying) {
  63022. if (this._streaming) {
  63023. if (this._htmlAudioElement) {
  63024. this._htmlAudioElement.pause();
  63025. // Test needed for Firefox or it will generate an Invalid State Error
  63026. if (this._htmlAudioElement.currentTime > 0) {
  63027. this._htmlAudioElement.currentTime = 0;
  63028. }
  63029. }
  63030. else {
  63031. this._streamingSource.disconnect();
  63032. }
  63033. }
  63034. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  63035. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  63036. this._soundSource.stop(stopTime);
  63037. this._soundSource.onended = function () { };
  63038. if (!this.isPaused) {
  63039. this._startOffset = 0;
  63040. }
  63041. }
  63042. this.isPlaying = false;
  63043. }
  63044. };
  63045. Sound.prototype.pause = function () {
  63046. if (this.isPlaying) {
  63047. this.isPaused = true;
  63048. if (this._streaming) {
  63049. if (this._htmlAudioElement) {
  63050. this._htmlAudioElement.pause();
  63051. }
  63052. else {
  63053. this._streamingSource.disconnect();
  63054. }
  63055. }
  63056. else if (BABYLON.Engine.audioEngine.audioContext) {
  63057. this.stop(0);
  63058. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  63059. }
  63060. }
  63061. };
  63062. Sound.prototype.setVolume = function (newVolume, time) {
  63063. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  63064. if (time && BABYLON.Engine.audioEngine.audioContext) {
  63065. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  63066. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  63067. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  63068. }
  63069. else {
  63070. this._soundGain.gain.value = newVolume;
  63071. }
  63072. }
  63073. this._volume = newVolume;
  63074. };
  63075. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  63076. this._playbackRate = newPlaybackRate;
  63077. if (this.isPlaying) {
  63078. if (this._streaming && this._htmlAudioElement) {
  63079. this._htmlAudioElement.playbackRate = this._playbackRate;
  63080. }
  63081. else if (this._soundSource) {
  63082. this._soundSource.playbackRate.value = this._playbackRate;
  63083. }
  63084. }
  63085. };
  63086. Sound.prototype.getVolume = function () {
  63087. return this._volume;
  63088. };
  63089. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  63090. var _this = this;
  63091. if (this._connectedMesh && this._registerFunc) {
  63092. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63093. this._registerFunc = null;
  63094. }
  63095. this._connectedMesh = meshToConnectTo;
  63096. if (!this.spatialSound) {
  63097. this.spatialSound = true;
  63098. this._createSpatialParameters();
  63099. if (this.isPlaying && this.loop) {
  63100. this.stop();
  63101. this.play();
  63102. }
  63103. }
  63104. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  63105. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  63106. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  63107. };
  63108. Sound.prototype.detachFromMesh = function () {
  63109. if (this._connectedMesh && this._registerFunc) {
  63110. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  63111. this._registerFunc = null;
  63112. this._connectedMesh = null;
  63113. }
  63114. };
  63115. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  63116. if (!node.getBoundingInfo) {
  63117. return;
  63118. }
  63119. var mesh = node;
  63120. var boundingInfo = mesh.getBoundingInfo();
  63121. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  63122. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  63123. this._updateDirection();
  63124. }
  63125. };
  63126. Sound.prototype.clone = function () {
  63127. var _this = this;
  63128. if (!this._streaming) {
  63129. var setBufferAndRun = function () {
  63130. if (_this._isReadyToPlay) {
  63131. clonedSound._audioBuffer = _this.getAudioBuffer();
  63132. clonedSound._isReadyToPlay = true;
  63133. if (clonedSound.autoplay) {
  63134. clonedSound.play();
  63135. }
  63136. }
  63137. else {
  63138. window.setTimeout(setBufferAndRun, 300);
  63139. }
  63140. };
  63141. var currentOptions = {
  63142. autoplay: this.autoplay, loop: this.loop,
  63143. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  63144. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  63145. refDistance: this.refDistance, distanceModel: this.distanceModel
  63146. };
  63147. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  63148. if (this.useCustomAttenuation) {
  63149. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  63150. }
  63151. clonedSound.setPosition(this._position);
  63152. clonedSound.setPlaybackRate(this._playbackRate);
  63153. setBufferAndRun();
  63154. return clonedSound;
  63155. }
  63156. // Can't clone a streaming sound
  63157. else {
  63158. return null;
  63159. }
  63160. };
  63161. Sound.prototype.getAudioBuffer = function () {
  63162. return this._audioBuffer;
  63163. };
  63164. Sound.prototype.serialize = function () {
  63165. var serializationObject = {
  63166. name: this.name,
  63167. url: this.name,
  63168. autoplay: this.autoplay,
  63169. loop: this.loop,
  63170. volume: this._volume,
  63171. spatialSound: this.spatialSound,
  63172. maxDistance: this.maxDistance,
  63173. rolloffFactor: this.rolloffFactor,
  63174. refDistance: this.refDistance,
  63175. distanceModel: this.distanceModel,
  63176. playbackRate: this._playbackRate,
  63177. panningModel: this._panningModel,
  63178. soundTrackId: this.soundTrackId
  63179. };
  63180. if (this.spatialSound) {
  63181. if (this._connectedMesh)
  63182. serializationObject.connectedMeshId = this._connectedMesh.id;
  63183. serializationObject.position = this._position.asArray();
  63184. serializationObject.refDistance = this.refDistance;
  63185. serializationObject.distanceModel = this.distanceModel;
  63186. serializationObject.isDirectional = this._isDirectional;
  63187. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63188. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63189. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63190. serializationObject.coneOuterGain = this._coneOuterGain;
  63191. }
  63192. return serializationObject;
  63193. };
  63194. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63195. var soundName = parsedSound.name;
  63196. var soundUrl;
  63197. if (parsedSound.url) {
  63198. soundUrl = rootUrl + parsedSound.url;
  63199. }
  63200. else {
  63201. soundUrl = rootUrl + soundName;
  63202. }
  63203. var options = {
  63204. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63205. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63206. rolloffFactor: parsedSound.rolloffFactor,
  63207. refDistance: parsedSound.refDistance,
  63208. distanceModel: parsedSound.distanceModel,
  63209. playbackRate: parsedSound.playbackRate
  63210. };
  63211. var newSound;
  63212. if (!sourceSound) {
  63213. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63214. scene._addPendingData(newSound);
  63215. }
  63216. else {
  63217. var setBufferAndRun = function () {
  63218. if (sourceSound._isReadyToPlay) {
  63219. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63220. newSound._isReadyToPlay = true;
  63221. if (newSound.autoplay) {
  63222. newSound.play();
  63223. }
  63224. }
  63225. else {
  63226. window.setTimeout(setBufferAndRun, 300);
  63227. }
  63228. };
  63229. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63230. setBufferAndRun();
  63231. }
  63232. if (parsedSound.position) {
  63233. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63234. newSound.setPosition(soundPosition);
  63235. }
  63236. if (parsedSound.isDirectional) {
  63237. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63238. if (parsedSound.localDirectionToMesh) {
  63239. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63240. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63241. }
  63242. }
  63243. if (parsedSound.connectedMeshId) {
  63244. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63245. if (connectedMesh) {
  63246. newSound.attachToMesh(connectedMesh);
  63247. }
  63248. }
  63249. return newSound;
  63250. };
  63251. return Sound;
  63252. }());
  63253. BABYLON.Sound = Sound;
  63254. })(BABYLON || (BABYLON = {}));
  63255. //# sourceMappingURL=babylon.sound.js.map
  63256. var BABYLON;
  63257. (function (BABYLON) {
  63258. var SoundTrack = /** @class */ (function () {
  63259. function SoundTrack(scene, options) {
  63260. this.id = -1;
  63261. this._isMainTrack = false;
  63262. this._isInitialized = false;
  63263. this._scene = scene;
  63264. this.soundCollection = new Array();
  63265. this._options = options;
  63266. if (!this._isMainTrack) {
  63267. this._scene.soundTracks.push(this);
  63268. this.id = this._scene.soundTracks.length - 1;
  63269. }
  63270. }
  63271. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63272. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63273. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63274. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63275. if (this._options) {
  63276. if (this._options.volume) {
  63277. this._outputAudioNode.gain.value = this._options.volume;
  63278. }
  63279. if (this._options.mainTrack) {
  63280. this._isMainTrack = this._options.mainTrack;
  63281. }
  63282. }
  63283. this._isInitialized = true;
  63284. }
  63285. };
  63286. SoundTrack.prototype.dispose = function () {
  63287. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63288. if (this._connectedAnalyser) {
  63289. this._connectedAnalyser.stopDebugCanvas();
  63290. }
  63291. while (this.soundCollection.length) {
  63292. this.soundCollection[0].dispose();
  63293. }
  63294. if (this._outputAudioNode) {
  63295. this._outputAudioNode.disconnect();
  63296. }
  63297. this._outputAudioNode = null;
  63298. }
  63299. };
  63300. SoundTrack.prototype.AddSound = function (sound) {
  63301. if (!this._isInitialized) {
  63302. this._initializeSoundTrackAudioGraph();
  63303. }
  63304. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63305. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63306. }
  63307. if (sound.soundTrackId) {
  63308. if (sound.soundTrackId === -1) {
  63309. this._scene.mainSoundTrack.RemoveSound(sound);
  63310. }
  63311. else {
  63312. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63313. }
  63314. }
  63315. this.soundCollection.push(sound);
  63316. sound.soundTrackId = this.id;
  63317. };
  63318. SoundTrack.prototype.RemoveSound = function (sound) {
  63319. var index = this.soundCollection.indexOf(sound);
  63320. if (index !== -1) {
  63321. this.soundCollection.splice(index, 1);
  63322. }
  63323. };
  63324. SoundTrack.prototype.setVolume = function (newVolume) {
  63325. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63326. this._outputAudioNode.gain.value = newVolume;
  63327. }
  63328. };
  63329. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63330. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63331. for (var i = 0; i < this.soundCollection.length; i++) {
  63332. this.soundCollection[i].switchPanningModelToHRTF();
  63333. }
  63334. }
  63335. };
  63336. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63337. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63338. for (var i = 0; i < this.soundCollection.length; i++) {
  63339. this.soundCollection[i].switchPanningModelToEqualPower();
  63340. }
  63341. }
  63342. };
  63343. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63344. if (this._connectedAnalyser) {
  63345. this._connectedAnalyser.stopDebugCanvas();
  63346. }
  63347. this._connectedAnalyser = analyser;
  63348. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63349. this._outputAudioNode.disconnect();
  63350. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63351. }
  63352. };
  63353. return SoundTrack;
  63354. }());
  63355. BABYLON.SoundTrack = SoundTrack;
  63356. })(BABYLON || (BABYLON = {}));
  63357. //# sourceMappingURL=babylon.soundtrack.js.map
  63358. var BABYLON;
  63359. (function (BABYLON) {
  63360. /**
  63361. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63362. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63363. */
  63364. var Analyser = /** @class */ (function () {
  63365. /**
  63366. * Creates a new analyser
  63367. * @param scene defines hosting scene
  63368. */
  63369. function Analyser(scene) {
  63370. /**
  63371. * Gets or sets the smoothing
  63372. * @ignorenaming
  63373. */
  63374. this.SMOOTHING = 0.75;
  63375. /**
  63376. * Gets or sets the FFT table size
  63377. * @ignorenaming
  63378. */
  63379. this.FFT_SIZE = 512;
  63380. /**
  63381. * Gets or sets the bar graph amplitude
  63382. * @ignorenaming
  63383. */
  63384. this.BARGRAPHAMPLITUDE = 256;
  63385. /**
  63386. * Gets or sets the position of the debug canvas
  63387. * @ignorenaming
  63388. */
  63389. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63390. /**
  63391. * Gets or sets the debug canvas size
  63392. * @ignorenaming
  63393. */
  63394. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63395. this._scene = scene;
  63396. this._audioEngine = BABYLON.Engine.audioEngine;
  63397. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63398. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63399. this._webAudioAnalyser.minDecibels = -140;
  63400. this._webAudioAnalyser.maxDecibels = 0;
  63401. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63402. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63403. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63404. }
  63405. }
  63406. /**
  63407. * Get the number of data values you will have to play with for the visualization
  63408. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63409. * @returns a number
  63410. */
  63411. Analyser.prototype.getFrequencyBinCount = function () {
  63412. if (this._audioEngine.canUseWebAudio) {
  63413. return this._webAudioAnalyser.frequencyBinCount;
  63414. }
  63415. else {
  63416. return 0;
  63417. }
  63418. };
  63419. /**
  63420. * Gets the current frequency data as a byte array
  63421. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63422. * @returns a Uint8Array
  63423. */
  63424. Analyser.prototype.getByteFrequencyData = function () {
  63425. if (this._audioEngine.canUseWebAudio) {
  63426. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63427. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63428. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63429. }
  63430. return this._byteFreqs;
  63431. };
  63432. /**
  63433. * Gets the current waveform as a byte array
  63434. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63435. * @returns a Uint8Array
  63436. */
  63437. Analyser.prototype.getByteTimeDomainData = function () {
  63438. if (this._audioEngine.canUseWebAudio) {
  63439. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63440. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63441. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63442. }
  63443. return this._byteTime;
  63444. };
  63445. /**
  63446. * Gets the current frequency data as a float array
  63447. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63448. * @returns a Float32Array
  63449. */
  63450. Analyser.prototype.getFloatFrequencyData = function () {
  63451. if (this._audioEngine.canUseWebAudio) {
  63452. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63453. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63454. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63455. }
  63456. return this._floatFreqs;
  63457. };
  63458. /**
  63459. * Renders the debug canvas
  63460. */
  63461. Analyser.prototype.drawDebugCanvas = function () {
  63462. var _this = this;
  63463. if (this._audioEngine.canUseWebAudio) {
  63464. if (!this._debugCanvas) {
  63465. this._debugCanvas = document.createElement("canvas");
  63466. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63467. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63468. this._debugCanvas.style.position = "absolute";
  63469. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63470. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63471. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63472. document.body.appendChild(this._debugCanvas);
  63473. this._registerFunc = function () {
  63474. _this.drawDebugCanvas();
  63475. };
  63476. this._scene.registerBeforeRender(this._registerFunc);
  63477. }
  63478. if (this._registerFunc && this._debugCanvasContext) {
  63479. var workingArray = this.getByteFrequencyData();
  63480. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63481. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63482. // Draw the frequency domain chart.
  63483. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63484. var value = workingArray[i];
  63485. var percent = value / this.BARGRAPHAMPLITUDE;
  63486. var height = this.DEBUGCANVASSIZE.height * percent;
  63487. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63488. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63489. var hue = i / this.getFrequencyBinCount() * 360;
  63490. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63491. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63492. }
  63493. }
  63494. }
  63495. };
  63496. /**
  63497. * Stops rendering the debug canvas and removes it
  63498. */
  63499. Analyser.prototype.stopDebugCanvas = function () {
  63500. if (this._debugCanvas) {
  63501. if (this._registerFunc) {
  63502. this._scene.unregisterBeforeRender(this._registerFunc);
  63503. this._registerFunc = null;
  63504. }
  63505. document.body.removeChild(this._debugCanvas);
  63506. this._debugCanvas = null;
  63507. this._debugCanvasContext = null;
  63508. }
  63509. };
  63510. /**
  63511. * Connects two audio nodes
  63512. * @param inputAudioNode defines first node to connect
  63513. * @param outputAudioNode defines second node to connect
  63514. */
  63515. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63516. if (this._audioEngine.canUseWebAudio) {
  63517. inputAudioNode.connect(this._webAudioAnalyser);
  63518. this._webAudioAnalyser.connect(outputAudioNode);
  63519. }
  63520. };
  63521. /**
  63522. * Releases all associated resources
  63523. */
  63524. Analyser.prototype.dispose = function () {
  63525. if (this._audioEngine.canUseWebAudio) {
  63526. this._webAudioAnalyser.disconnect();
  63527. }
  63528. };
  63529. return Analyser;
  63530. }());
  63531. BABYLON.Analyser = Analyser;
  63532. })(BABYLON || (BABYLON = {}));
  63533. //# sourceMappingURL=babylon.analyser.js.map
  63534. var BABYLON;
  63535. (function (BABYLON) {
  63536. var CubeTexture = /** @class */ (function (_super) {
  63537. __extends(CubeTexture, _super);
  63538. /**
  63539. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63540. * as prefiltered data.
  63541. * @param rootUrl defines the url of the texture or the root name of the six images
  63542. * @param scene defines the scene the texture is attached to
  63543. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63544. * @param noMipmap defines if mipmaps should be created or not
  63545. * @param files defines the six files to load for the different faces
  63546. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63547. * @param onError defines a callback triggered in case of error during load
  63548. * @param format defines the internal format to use for the texture once loaded
  63549. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63550. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63551. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63552. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63553. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63554. * @return the cube texture
  63555. */
  63556. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63557. if (extensions === void 0) { extensions = null; }
  63558. if (noMipmap === void 0) { noMipmap = false; }
  63559. if (files === void 0) { files = null; }
  63560. if (onLoad === void 0) { onLoad = null; }
  63561. if (onError === void 0) { onError = null; }
  63562. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63563. if (prefiltered === void 0) { prefiltered = false; }
  63564. if (forcedExtension === void 0) { forcedExtension = null; }
  63565. if (createPolynomials === void 0) { createPolynomials = false; }
  63566. if (lodScale === void 0) { lodScale = 0.8; }
  63567. if (lodOffset === void 0) { lodOffset = 0; }
  63568. var _this = _super.call(this, scene) || this;
  63569. /**
  63570. * Gets or sets the center of the bounding box associated with the cube texture
  63571. * It must define where the camera used to render the texture was set
  63572. */
  63573. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63574. _this._rotationY = 0;
  63575. /** @hidden */
  63576. _this._prefiltered = false;
  63577. _this.name = rootUrl;
  63578. _this.url = rootUrl;
  63579. _this._noMipmap = noMipmap;
  63580. _this.hasAlpha = false;
  63581. _this._format = format;
  63582. _this.isCube = true;
  63583. _this._textureMatrix = BABYLON.Matrix.Identity();
  63584. _this._createPolynomials = createPolynomials;
  63585. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63586. if (!rootUrl && !files) {
  63587. return _this;
  63588. }
  63589. var lastDot = rootUrl.lastIndexOf(".");
  63590. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63591. var isDDS = (extension === ".dds");
  63592. var isEnv = (extension === ".env");
  63593. if (isEnv) {
  63594. _this.gammaSpace = false;
  63595. _this._prefiltered = false;
  63596. }
  63597. else {
  63598. _this._prefiltered = prefiltered;
  63599. if (prefiltered) {
  63600. _this.gammaSpace = false;
  63601. }
  63602. }
  63603. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63604. if (!files) {
  63605. if (!isEnv && !isDDS && !extensions) {
  63606. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63607. }
  63608. files = [];
  63609. if (extensions) {
  63610. for (var index = 0; index < extensions.length; index++) {
  63611. files.push(rootUrl + extensions[index]);
  63612. }
  63613. }
  63614. }
  63615. _this._files = files;
  63616. if (!_this._texture) {
  63617. if (!scene.useDelayedTextureLoading) {
  63618. if (prefiltered) {
  63619. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63620. }
  63621. else {
  63622. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63623. }
  63624. }
  63625. else {
  63626. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63627. }
  63628. }
  63629. else if (onLoad) {
  63630. if (_this._texture.isReady) {
  63631. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63632. }
  63633. else {
  63634. _this._texture.onLoadedObservable.add(onLoad);
  63635. }
  63636. }
  63637. return _this;
  63638. }
  63639. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63640. get: function () {
  63641. return this._boundingBoxSize;
  63642. },
  63643. /**
  63644. * Gets or sets the size of the bounding box associated with the cube texture
  63645. * When defined, the cubemap will switch to local mode
  63646. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63647. * @example https://www.babylonjs-playground.com/#RNASML
  63648. */
  63649. set: function (value) {
  63650. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63651. return;
  63652. }
  63653. this._boundingBoxSize = value;
  63654. var scene = this.getScene();
  63655. if (scene) {
  63656. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63657. }
  63658. },
  63659. enumerable: true,
  63660. configurable: true
  63661. });
  63662. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63663. /**
  63664. * Gets texture matrix rotation angle around Y axis radians.
  63665. */
  63666. get: function () {
  63667. return this._rotationY;
  63668. },
  63669. /**
  63670. * Sets texture matrix rotation angle around Y axis in radians.
  63671. */
  63672. set: function (value) {
  63673. this._rotationY = value;
  63674. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63675. },
  63676. enumerable: true,
  63677. configurable: true
  63678. });
  63679. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63680. var rootUrlKey = "";
  63681. files.forEach(function (url) { return rootUrlKey += url; });
  63682. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63683. };
  63684. /**
  63685. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63686. * @param url defines the url of the prefiltered texture
  63687. * @param scene defines the scene the texture is attached to
  63688. * @param forcedExtension defines the extension of the file if different from the url
  63689. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63690. * @return the prefiltered texture
  63691. */
  63692. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63693. if (forcedExtension === void 0) { forcedExtension = null; }
  63694. if (createPolynomials === void 0) { createPolynomials = true; }
  63695. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63696. };
  63697. // Methods
  63698. CubeTexture.prototype.delayLoad = function () {
  63699. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63700. return;
  63701. }
  63702. var scene = this.getScene();
  63703. if (!scene) {
  63704. return;
  63705. }
  63706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63707. this._texture = this._getFromCache(this.url, this._noMipmap);
  63708. if (!this._texture) {
  63709. if (this._prefiltered) {
  63710. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63711. }
  63712. else {
  63713. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63714. }
  63715. }
  63716. };
  63717. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63718. return this._textureMatrix;
  63719. };
  63720. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63721. this._textureMatrix = value;
  63722. };
  63723. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63724. var texture = BABYLON.SerializationHelper.Parse(function () {
  63725. var prefiltered = false;
  63726. if (parsedTexture.prefiltered) {
  63727. prefiltered = parsedTexture.prefiltered;
  63728. }
  63729. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63730. }, parsedTexture, scene);
  63731. // Local Cubemaps
  63732. if (parsedTexture.boundingBoxPosition) {
  63733. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63734. }
  63735. if (parsedTexture.boundingBoxSize) {
  63736. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63737. }
  63738. // Animations
  63739. if (parsedTexture.animations) {
  63740. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63741. var parsedAnimation = parsedTexture.animations[animationIndex];
  63742. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63743. }
  63744. }
  63745. return texture;
  63746. };
  63747. CubeTexture.prototype.clone = function () {
  63748. var _this = this;
  63749. return BABYLON.SerializationHelper.Clone(function () {
  63750. var scene = _this.getScene();
  63751. if (!scene) {
  63752. return _this;
  63753. }
  63754. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63755. }, this);
  63756. };
  63757. __decorate([
  63758. BABYLON.serialize("rotationY")
  63759. ], CubeTexture.prototype, "_rotationY", void 0);
  63760. return CubeTexture;
  63761. }(BABYLON.BaseTexture));
  63762. BABYLON.CubeTexture = CubeTexture;
  63763. })(BABYLON || (BABYLON = {}));
  63764. //# sourceMappingURL=babylon.cubeTexture.js.map
  63765. var BABYLON;
  63766. (function (BABYLON) {
  63767. /**
  63768. * Raw cube texture where the raw buffers are passed in
  63769. */
  63770. var RawCubeTexture = /** @class */ (function (_super) {
  63771. __extends(RawCubeTexture, _super);
  63772. /**
  63773. * Creates a cube texture where the raw buffers are passed in.
  63774. * @param scene defines the scene the texture is attached to
  63775. * @param data defines the array of data to use to create each face
  63776. * @param size defines the size of the textures
  63777. * @param format defines the format of the data
  63778. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  63779. * @param generateMipMaps defines if the engine should generate the mip levels
  63780. * @param invertY defines if data must be stored with Y axis inverted
  63781. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  63782. * @param compression defines the compression used (null by default)
  63783. */
  63784. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  63785. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63786. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63787. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63788. if (invertY === void 0) { invertY = false; }
  63789. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63790. if (compression === void 0) { compression = null; }
  63791. var _this = _super.call(this, "", scene) || this;
  63792. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  63793. return _this;
  63794. }
  63795. /**
  63796. * Updates the raw cube texture.
  63797. * @param data defines the data to store
  63798. * @param format defines the data format
  63799. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  63800. * @param invertY defines if data must be stored with Y axis inverted
  63801. * @param compression defines the compression used (null by default)
  63802. * @param level defines which level of the texture to update
  63803. */
  63804. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  63805. if (compression === void 0) { compression = null; }
  63806. if (level === void 0) { level = 0; }
  63807. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  63808. };
  63809. /**
  63810. * Updates a raw cube texture with RGBD encoded data.
  63811. * @param data defines the array of data [mipmap][face] to use to create each face
  63812. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  63813. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63814. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63815. * @returns a promsie that resolves when the operation is complete
  63816. */
  63817. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  63818. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  63819. if (lodScale === void 0) { lodScale = 0.8; }
  63820. if (lodOffset === void 0) { lodOffset = 0; }
  63821. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  63822. };
  63823. /**
  63824. * Clones the raw cube texture.
  63825. * @return a new cube texture
  63826. */
  63827. RawCubeTexture.prototype.clone = function () {
  63828. var _this = this;
  63829. return BABYLON.SerializationHelper.Clone(function () {
  63830. var scene = _this.getScene();
  63831. var internalTexture = _this._texture;
  63832. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  63833. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  63834. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  63835. }
  63836. return texture;
  63837. }, this);
  63838. };
  63839. /** @hidden */
  63840. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  63841. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  63842. internalTexture._bufferViewArrayArray = data;
  63843. internalTexture._lodGenerationScale = lodScale;
  63844. internalTexture._lodGenerationOffset = lodOffset;
  63845. internalTexture._sphericalPolynomial = sphericalPolynomial;
  63846. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  63847. internalTexture.isReady = true;
  63848. });
  63849. };
  63850. return RawCubeTexture;
  63851. }(BABYLON.CubeTexture));
  63852. BABYLON.RawCubeTexture = RawCubeTexture;
  63853. })(BABYLON || (BABYLON = {}));
  63854. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  63855. var BABYLON;
  63856. (function (BABYLON) {
  63857. var RenderTargetTexture = /** @class */ (function (_super) {
  63858. __extends(RenderTargetTexture, _super);
  63859. /**
  63860. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63861. * or used a shadow, depth texture...
  63862. * @param name The friendly name of the texture
  63863. * @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)
  63864. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63865. * @param generateMipMaps True if mip maps need to be generated after render.
  63866. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63867. * @param type The type of the buffer in the RTT (int, half float, float...)
  63868. * @param isCube True if a cube texture needs to be created
  63869. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63870. * @param generateDepthBuffer True to generate a depth buffer
  63871. * @param generateStencilBuffer True to generate a stencil buffer
  63872. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63873. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63874. */
  63875. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63876. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63877. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63878. if (isCube === void 0) { isCube = false; }
  63879. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63880. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63881. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63882. if (isMulti === void 0) { isMulti = false; }
  63883. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63884. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63885. _this.isCube = isCube;
  63886. /**
  63887. * Use this list to define the list of mesh you want to render.
  63888. */
  63889. _this.renderList = new Array();
  63890. _this.renderParticles = true;
  63891. _this.renderSprites = false;
  63892. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63893. _this.ignoreCameraViewport = false;
  63894. // Events
  63895. /**
  63896. * An event triggered when the texture is unbind.
  63897. */
  63898. _this.onBeforeBindObservable = new BABYLON.Observable();
  63899. /**
  63900. * An event triggered when the texture is unbind.
  63901. */
  63902. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63903. /**
  63904. * An event triggered before rendering the texture
  63905. */
  63906. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63907. /**
  63908. * An event triggered after rendering the texture
  63909. */
  63910. _this.onAfterRenderObservable = new BABYLON.Observable();
  63911. /**
  63912. * An event triggered after the texture clear
  63913. */
  63914. _this.onClearObservable = new BABYLON.Observable();
  63915. _this._currentRefreshId = -1;
  63916. _this._refreshRate = 1;
  63917. _this._samples = 1;
  63918. /**
  63919. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63920. * It must define where the camera used to render the texture is set
  63921. */
  63922. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63923. scene = _this.getScene();
  63924. if (!scene) {
  63925. return _this;
  63926. }
  63927. _this._engine = scene.getEngine();
  63928. _this.name = name;
  63929. _this.isRenderTarget = true;
  63930. _this._initialSizeParameter = size;
  63931. _this._processSizeParameter(size);
  63932. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63933. });
  63934. _this._generateMipMaps = generateMipMaps ? true : false;
  63935. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63936. // Rendering groups
  63937. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63938. if (isMulti) {
  63939. return _this;
  63940. }
  63941. _this._renderTargetOptions = {
  63942. generateMipMaps: generateMipMaps,
  63943. type: type,
  63944. format: format,
  63945. samplingMode: samplingMode,
  63946. generateDepthBuffer: generateDepthBuffer,
  63947. generateStencilBuffer: generateStencilBuffer
  63948. };
  63949. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63950. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63951. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63952. }
  63953. if (isCube) {
  63954. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63955. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63956. _this._textureMatrix = BABYLON.Matrix.Identity();
  63957. }
  63958. else {
  63959. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63960. }
  63961. return _this;
  63962. }
  63963. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63964. get: function () {
  63965. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63966. },
  63967. enumerable: true,
  63968. configurable: true
  63969. });
  63970. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63971. get: function () {
  63972. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63973. },
  63974. enumerable: true,
  63975. configurable: true
  63976. });
  63977. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63978. get: function () {
  63979. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63980. },
  63981. enumerable: true,
  63982. configurable: true
  63983. });
  63984. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63985. set: function (callback) {
  63986. if (this._onAfterUnbindObserver) {
  63987. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63988. }
  63989. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63995. set: function (callback) {
  63996. if (this._onBeforeRenderObserver) {
  63997. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63998. }
  63999. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64000. },
  64001. enumerable: true,
  64002. configurable: true
  64003. });
  64004. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  64005. set: function (callback) {
  64006. if (this._onAfterRenderObserver) {
  64007. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64008. }
  64009. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64010. },
  64011. enumerable: true,
  64012. configurable: true
  64013. });
  64014. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  64015. set: function (callback) {
  64016. if (this._onClearObserver) {
  64017. this.onClearObservable.remove(this._onClearObserver);
  64018. }
  64019. this._onClearObserver = this.onClearObservable.add(callback);
  64020. },
  64021. enumerable: true,
  64022. configurable: true
  64023. });
  64024. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  64025. get: function () {
  64026. return this._renderTargetOptions;
  64027. },
  64028. enumerable: true,
  64029. configurable: true
  64030. });
  64031. RenderTargetTexture.prototype._onRatioRescale = function () {
  64032. if (this._sizeRatio) {
  64033. this.resize(this._initialSizeParameter);
  64034. }
  64035. };
  64036. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  64037. get: function () {
  64038. return this._boundingBoxSize;
  64039. },
  64040. /**
  64041. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  64042. * When defined, the cubemap will switch to local mode
  64043. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  64044. * @example https://www.babylonjs-playground.com/#RNASML
  64045. */
  64046. set: function (value) {
  64047. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  64048. return;
  64049. }
  64050. this._boundingBoxSize = value;
  64051. var scene = this.getScene();
  64052. if (scene) {
  64053. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  64054. }
  64055. },
  64056. enumerable: true,
  64057. configurable: true
  64058. });
  64059. /**
  64060. * Creates a depth stencil texture.
  64061. * This is only available in WebGL 2 or with the depth texture extension available.
  64062. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  64063. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  64064. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  64065. */
  64066. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  64067. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  64068. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  64069. if (generateStencil === void 0) { generateStencil = false; }
  64070. if (!this.getScene()) {
  64071. return;
  64072. }
  64073. var engine = this.getScene().getEngine();
  64074. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  64075. bilinearFiltering: bilinearFiltering,
  64076. comparisonFunction: comparisonFunction,
  64077. generateStencil: generateStencil,
  64078. isCube: this.isCube
  64079. });
  64080. engine.setFrameBufferDepthStencilTexture(this);
  64081. };
  64082. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  64083. if (size.ratio) {
  64084. this._sizeRatio = size.ratio;
  64085. this._size = {
  64086. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  64087. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  64088. };
  64089. }
  64090. else {
  64091. this._size = size;
  64092. }
  64093. };
  64094. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  64095. get: function () {
  64096. return this._samples;
  64097. },
  64098. set: function (value) {
  64099. if (this._samples === value) {
  64100. return;
  64101. }
  64102. var scene = this.getScene();
  64103. if (!scene) {
  64104. return;
  64105. }
  64106. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  64107. },
  64108. enumerable: true,
  64109. configurable: true
  64110. });
  64111. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  64112. this._currentRefreshId = -1;
  64113. };
  64114. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  64115. get: function () {
  64116. return this._refreshRate;
  64117. },
  64118. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  64119. set: function (value) {
  64120. this._refreshRate = value;
  64121. this.resetRefreshCounter();
  64122. },
  64123. enumerable: true,
  64124. configurable: true
  64125. });
  64126. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  64127. if (!this._postProcessManager) {
  64128. var scene = this.getScene();
  64129. if (!scene) {
  64130. return;
  64131. }
  64132. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  64133. this._postProcesses = new Array();
  64134. }
  64135. this._postProcesses.push(postProcess);
  64136. this._postProcesses[0].autoClear = false;
  64137. };
  64138. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  64139. if (!this._postProcesses) {
  64140. return;
  64141. }
  64142. if (dispose) {
  64143. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  64144. var postProcess = _a[_i];
  64145. postProcess.dispose();
  64146. }
  64147. }
  64148. this._postProcesses = [];
  64149. };
  64150. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  64151. if (!this._postProcesses) {
  64152. return;
  64153. }
  64154. var index = this._postProcesses.indexOf(postProcess);
  64155. if (index === -1) {
  64156. return;
  64157. }
  64158. this._postProcesses.splice(index, 1);
  64159. if (this._postProcesses.length > 0) {
  64160. this._postProcesses[0].autoClear = false;
  64161. }
  64162. };
  64163. RenderTargetTexture.prototype._shouldRender = function () {
  64164. if (this._currentRefreshId === -1) { // At least render once
  64165. this._currentRefreshId = 1;
  64166. return true;
  64167. }
  64168. if (this.refreshRate === this._currentRefreshId) {
  64169. this._currentRefreshId = 1;
  64170. return true;
  64171. }
  64172. this._currentRefreshId++;
  64173. return false;
  64174. };
  64175. RenderTargetTexture.prototype.getRenderSize = function () {
  64176. if (this._size.width) {
  64177. return this._size.width;
  64178. }
  64179. return this._size;
  64180. };
  64181. RenderTargetTexture.prototype.getRenderWidth = function () {
  64182. if (this._size.width) {
  64183. return this._size.width;
  64184. }
  64185. return this._size;
  64186. };
  64187. RenderTargetTexture.prototype.getRenderHeight = function () {
  64188. if (this._size.width) {
  64189. return this._size.height;
  64190. }
  64191. return this._size;
  64192. };
  64193. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  64194. get: function () {
  64195. return true;
  64196. },
  64197. enumerable: true,
  64198. configurable: true
  64199. });
  64200. RenderTargetTexture.prototype.scale = function (ratio) {
  64201. var newSize = this.getRenderSize() * ratio;
  64202. this.resize(newSize);
  64203. };
  64204. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  64205. if (this.isCube) {
  64206. return this._textureMatrix;
  64207. }
  64208. return _super.prototype.getReflectionTextureMatrix.call(this);
  64209. };
  64210. RenderTargetTexture.prototype.resize = function (size) {
  64211. this.releaseInternalTexture();
  64212. var scene = this.getScene();
  64213. if (!scene) {
  64214. return;
  64215. }
  64216. this._processSizeParameter(size);
  64217. if (this.isCube) {
  64218. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  64219. }
  64220. else {
  64221. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  64222. }
  64223. };
  64224. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  64225. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  64226. if (dumpForDebug === void 0) { dumpForDebug = false; }
  64227. var scene = this.getScene();
  64228. if (!scene) {
  64229. return;
  64230. }
  64231. var engine = scene.getEngine();
  64232. if (this.useCameraPostProcesses !== undefined) {
  64233. useCameraPostProcess = this.useCameraPostProcesses;
  64234. }
  64235. if (this._waitingRenderList) {
  64236. this.renderList = [];
  64237. for (var index = 0; index < this._waitingRenderList.length; index++) {
  64238. var id = this._waitingRenderList[index];
  64239. var mesh_1 = scene.getMeshByID(id);
  64240. if (mesh_1) {
  64241. this.renderList.push(mesh_1);
  64242. }
  64243. }
  64244. delete this._waitingRenderList;
  64245. }
  64246. // Is predicate defined?
  64247. if (this.renderListPredicate) {
  64248. if (this.renderList) {
  64249. this.renderList.splice(0); // Clear previous renderList
  64250. }
  64251. else {
  64252. this.renderList = [];
  64253. }
  64254. var scene = this.getScene();
  64255. if (!scene) {
  64256. return;
  64257. }
  64258. var sceneMeshes = scene.meshes;
  64259. for (var index = 0; index < sceneMeshes.length; index++) {
  64260. var mesh = sceneMeshes[index];
  64261. if (this.renderListPredicate(mesh)) {
  64262. this.renderList.push(mesh);
  64263. }
  64264. }
  64265. }
  64266. this.onBeforeBindObservable.notifyObservers(this);
  64267. // Set custom projection.
  64268. // Needs to be before binding to prevent changing the aspect ratio.
  64269. var camera;
  64270. if (this.activeCamera) {
  64271. camera = this.activeCamera;
  64272. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64273. if (this.activeCamera !== scene.activeCamera) {
  64274. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64275. }
  64276. }
  64277. else {
  64278. camera = scene.activeCamera;
  64279. if (camera) {
  64280. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64281. }
  64282. }
  64283. // Prepare renderingManager
  64284. this._renderingManager.reset();
  64285. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64286. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64287. var sceneRenderId = scene.getRenderId();
  64288. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64289. var mesh = currentRenderList[meshIndex];
  64290. if (mesh) {
  64291. if (!mesh.isReady(this.refreshRate === 0)) {
  64292. this.resetRefreshCounter();
  64293. continue;
  64294. }
  64295. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64296. var isMasked = void 0;
  64297. if (!this.renderList && camera) {
  64298. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64299. }
  64300. else {
  64301. isMasked = false;
  64302. }
  64303. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64304. mesh._activate(sceneRenderId);
  64305. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64306. var subMesh = mesh.subMeshes[subIndex];
  64307. scene._activeIndices.addCount(subMesh.indexCount, false);
  64308. this._renderingManager.dispatch(subMesh, mesh);
  64309. }
  64310. }
  64311. }
  64312. }
  64313. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64314. var particleSystem = scene.particleSystems[particleIndex];
  64315. var emitter = particleSystem.emitter;
  64316. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64317. continue;
  64318. }
  64319. if (currentRenderList.indexOf(emitter) >= 0) {
  64320. this._renderingManager.dispatchParticles(particleSystem);
  64321. }
  64322. }
  64323. if (this.isCube) {
  64324. for (var face = 0; face < 6; face++) {
  64325. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64326. scene.incrementRenderId();
  64327. scene.resetCachedMaterial();
  64328. }
  64329. }
  64330. else {
  64331. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64332. }
  64333. this.onAfterUnbindObservable.notifyObservers(this);
  64334. if (scene.activeCamera) {
  64335. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64336. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64337. }
  64338. engine.setViewport(scene.activeCamera.viewport);
  64339. }
  64340. scene.resetCachedMaterial();
  64341. };
  64342. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64343. var minimum = 128;
  64344. var x = renderDimension * scale;
  64345. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64346. // Ensure we don't exceed the render dimension (while staying POT)
  64347. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64348. };
  64349. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64350. var _this = this;
  64351. if (!this._texture) {
  64352. return;
  64353. }
  64354. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64355. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64356. });
  64357. };
  64358. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64359. var scene = this.getScene();
  64360. if (!scene) {
  64361. return;
  64362. }
  64363. var engine = scene.getEngine();
  64364. if (!this._texture) {
  64365. return;
  64366. }
  64367. // Bind
  64368. if (this._postProcessManager) {
  64369. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64370. }
  64371. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64372. if (this._texture) {
  64373. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64374. }
  64375. }
  64376. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64377. // Clear
  64378. if (this.onClearObservable.hasObservers()) {
  64379. this.onClearObservable.notifyObservers(engine);
  64380. }
  64381. else {
  64382. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64383. }
  64384. if (!this._doNotChangeAspectRatio) {
  64385. scene.updateTransformMatrix(true);
  64386. }
  64387. // Render
  64388. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64389. if (this._postProcessManager) {
  64390. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64391. }
  64392. else if (useCameraPostProcess) {
  64393. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64394. }
  64395. if (!this._doNotChangeAspectRatio) {
  64396. scene.updateTransformMatrix(true);
  64397. }
  64398. // Dump ?
  64399. if (dumpForDebug) {
  64400. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64401. }
  64402. // Unbind
  64403. if (!this.isCube || faceIndex === 5) {
  64404. if (this.isCube) {
  64405. if (faceIndex === 5) {
  64406. engine.generateMipMapsForCubemap(this._texture);
  64407. }
  64408. }
  64409. this.unbindFrameBuffer(engine, faceIndex);
  64410. }
  64411. else {
  64412. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64413. }
  64414. };
  64415. /**
  64416. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64417. * This allowed control for front to back rendering or reversly depending of the special needs.
  64418. *
  64419. * @param renderingGroupId The rendering group id corresponding to its index
  64420. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64421. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64422. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64423. */
  64424. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64425. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64426. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64427. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64428. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64429. };
  64430. /**
  64431. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64432. *
  64433. * @param renderingGroupId The rendering group id corresponding to its index
  64434. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64435. */
  64436. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64437. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64438. };
  64439. RenderTargetTexture.prototype.clone = function () {
  64440. var textureSize = this.getSize();
  64441. 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);
  64442. // Base texture
  64443. newTexture.hasAlpha = this.hasAlpha;
  64444. newTexture.level = this.level;
  64445. // RenderTarget Texture
  64446. newTexture.coordinatesMode = this.coordinatesMode;
  64447. if (this.renderList) {
  64448. newTexture.renderList = this.renderList.slice(0);
  64449. }
  64450. return newTexture;
  64451. };
  64452. RenderTargetTexture.prototype.serialize = function () {
  64453. if (!this.name) {
  64454. return null;
  64455. }
  64456. var serializationObject = _super.prototype.serialize.call(this);
  64457. serializationObject.renderTargetSize = this.getRenderSize();
  64458. serializationObject.renderList = [];
  64459. if (this.renderList) {
  64460. for (var index = 0; index < this.renderList.length; index++) {
  64461. serializationObject.renderList.push(this.renderList[index].id);
  64462. }
  64463. }
  64464. return serializationObject;
  64465. };
  64466. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64467. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64468. var objBuffer = this.getInternalTexture();
  64469. var scene = this.getScene();
  64470. if (objBuffer && scene) {
  64471. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64472. }
  64473. };
  64474. RenderTargetTexture.prototype.dispose = function () {
  64475. if (this._postProcessManager) {
  64476. this._postProcessManager.dispose();
  64477. this._postProcessManager = null;
  64478. }
  64479. this.clearPostProcesses(true);
  64480. if (this._resizeObserver) {
  64481. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64482. this._resizeObserver = null;
  64483. }
  64484. this.renderList = null;
  64485. // Remove from custom render targets
  64486. var scene = this.getScene();
  64487. if (!scene) {
  64488. return;
  64489. }
  64490. var index = scene.customRenderTargets.indexOf(this);
  64491. if (index >= 0) {
  64492. scene.customRenderTargets.splice(index, 1);
  64493. }
  64494. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64495. var camera = _a[_i];
  64496. index = camera.customRenderTargets.indexOf(this);
  64497. if (index >= 0) {
  64498. camera.customRenderTargets.splice(index, 1);
  64499. }
  64500. }
  64501. _super.prototype.dispose.call(this);
  64502. };
  64503. RenderTargetTexture.prototype._rebuild = function () {
  64504. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64505. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64506. }
  64507. if (this._postProcessManager) {
  64508. this._postProcessManager._rebuild();
  64509. }
  64510. };
  64511. /**
  64512. * Clear the info related to rendering groups preventing retention point in material dispose.
  64513. */
  64514. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64515. if (this._renderingManager) {
  64516. this._renderingManager.freeRenderingGroups();
  64517. }
  64518. };
  64519. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64520. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64521. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64522. return RenderTargetTexture;
  64523. }(BABYLON.Texture));
  64524. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64525. })(BABYLON || (BABYLON = {}));
  64526. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64527. var BABYLON;
  64528. (function (BABYLON) {
  64529. ;
  64530. var MultiRenderTarget = /** @class */ (function (_super) {
  64531. __extends(MultiRenderTarget, _super);
  64532. function MultiRenderTarget(name, size, count, scene, options) {
  64533. var _this = this;
  64534. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64535. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64536. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64537. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64538. _this._engine = scene.getEngine();
  64539. if (!_this.isSupported) {
  64540. _this.dispose();
  64541. return;
  64542. }
  64543. var types = [];
  64544. var samplingModes = [];
  64545. for (var i = 0; i < count; i++) {
  64546. if (options && options.types && options.types[i] !== undefined) {
  64547. types.push(options.types[i]);
  64548. }
  64549. else {
  64550. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64551. }
  64552. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64553. samplingModes.push(options.samplingModes[i]);
  64554. }
  64555. else {
  64556. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64557. }
  64558. }
  64559. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64560. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64561. _this._size = size;
  64562. _this._multiRenderTargetOptions = {
  64563. samplingModes: samplingModes,
  64564. generateMipMaps: generateMipMaps,
  64565. generateDepthBuffer: generateDepthBuffer,
  64566. generateStencilBuffer: generateStencilBuffer,
  64567. generateDepthTexture: generateDepthTexture,
  64568. types: types,
  64569. textureCount: count
  64570. };
  64571. _this._createInternalTextures();
  64572. _this._createTextures();
  64573. return _this;
  64574. }
  64575. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64576. get: function () {
  64577. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64578. },
  64579. enumerable: true,
  64580. configurable: true
  64581. });
  64582. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64583. get: function () {
  64584. return this._textures;
  64585. },
  64586. enumerable: true,
  64587. configurable: true
  64588. });
  64589. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64590. get: function () {
  64591. return this._textures[this._textures.length - 1];
  64592. },
  64593. enumerable: true,
  64594. configurable: true
  64595. });
  64596. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64597. set: function (wrap) {
  64598. if (this._textures) {
  64599. for (var i = 0; i < this._textures.length; i++) {
  64600. this._textures[i].wrapU = wrap;
  64601. }
  64602. }
  64603. },
  64604. enumerable: true,
  64605. configurable: true
  64606. });
  64607. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64608. set: function (wrap) {
  64609. if (this._textures) {
  64610. for (var i = 0; i < this._textures.length; i++) {
  64611. this._textures[i].wrapV = wrap;
  64612. }
  64613. }
  64614. },
  64615. enumerable: true,
  64616. configurable: true
  64617. });
  64618. MultiRenderTarget.prototype._rebuild = function () {
  64619. this.releaseInternalTextures();
  64620. this._createInternalTextures();
  64621. for (var i = 0; i < this._internalTextures.length; i++) {
  64622. var texture = this._textures[i];
  64623. texture._texture = this._internalTextures[i];
  64624. }
  64625. // Keeps references to frame buffer and stencil/depth buffer
  64626. this._texture = this._internalTextures[0];
  64627. };
  64628. MultiRenderTarget.prototype._createInternalTextures = function () {
  64629. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64630. };
  64631. MultiRenderTarget.prototype._createTextures = function () {
  64632. this._textures = [];
  64633. for (var i = 0; i < this._internalTextures.length; i++) {
  64634. var texture = new BABYLON.Texture(null, this.getScene());
  64635. texture._texture = this._internalTextures[i];
  64636. this._textures.push(texture);
  64637. }
  64638. // Keeps references to frame buffer and stencil/depth buffer
  64639. this._texture = this._internalTextures[0];
  64640. };
  64641. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64642. get: function () {
  64643. return this._samples;
  64644. },
  64645. set: function (value) {
  64646. if (this._samples === value) {
  64647. return;
  64648. }
  64649. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64650. },
  64651. enumerable: true,
  64652. configurable: true
  64653. });
  64654. MultiRenderTarget.prototype.resize = function (size) {
  64655. this.releaseInternalTextures();
  64656. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64657. this._createInternalTextures();
  64658. };
  64659. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64660. var _this = this;
  64661. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64662. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64663. });
  64664. };
  64665. MultiRenderTarget.prototype.dispose = function () {
  64666. this.releaseInternalTextures();
  64667. _super.prototype.dispose.call(this);
  64668. };
  64669. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64670. if (!this._internalTextures) {
  64671. return;
  64672. }
  64673. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64674. if (this._internalTextures[i] !== undefined) {
  64675. this._internalTextures[i].dispose();
  64676. this._internalTextures.splice(i, 1);
  64677. }
  64678. }
  64679. };
  64680. return MultiRenderTarget;
  64681. }(BABYLON.RenderTargetTexture));
  64682. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64683. })(BABYLON || (BABYLON = {}));
  64684. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64685. var BABYLON;
  64686. (function (BABYLON) {
  64687. var MirrorTexture = /** @class */ (function (_super) {
  64688. __extends(MirrorTexture, _super);
  64689. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64690. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64691. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64692. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64693. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64694. _this.scene = scene;
  64695. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64696. _this._transformMatrix = BABYLON.Matrix.Zero();
  64697. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64698. _this._adaptiveBlurKernel = 0;
  64699. _this._blurKernelX = 0;
  64700. _this._blurKernelY = 0;
  64701. _this._blurRatio = 1.0;
  64702. _this.ignoreCameraViewport = true;
  64703. _this._updateGammaSpace();
  64704. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64705. _this._updateGammaSpace;
  64706. });
  64707. _this.onBeforeRenderObservable.add(function () {
  64708. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64709. _this._savedViewMatrix = scene.getViewMatrix();
  64710. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64711. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64712. scene.clipPlane = _this.mirrorPlane;
  64713. scene.getEngine().cullBackFaces = false;
  64714. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64715. });
  64716. _this.onAfterRenderObservable.add(function () {
  64717. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64718. scene.getEngine().cullBackFaces = true;
  64719. scene._mirroredCameraPosition = null;
  64720. delete scene.clipPlane;
  64721. });
  64722. return _this;
  64723. }
  64724. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64725. get: function () {
  64726. return this._blurRatio;
  64727. },
  64728. set: function (value) {
  64729. if (this._blurRatio === value) {
  64730. return;
  64731. }
  64732. this._blurRatio = value;
  64733. this._preparePostProcesses();
  64734. },
  64735. enumerable: true,
  64736. configurable: true
  64737. });
  64738. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64739. set: function (value) {
  64740. this._adaptiveBlurKernel = value;
  64741. this._autoComputeBlurKernel();
  64742. },
  64743. enumerable: true,
  64744. configurable: true
  64745. });
  64746. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64747. set: function (value) {
  64748. this.blurKernelX = value;
  64749. this.blurKernelY = value;
  64750. },
  64751. enumerable: true,
  64752. configurable: true
  64753. });
  64754. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64755. get: function () {
  64756. return this._blurKernelX;
  64757. },
  64758. set: function (value) {
  64759. if (this._blurKernelX === value) {
  64760. return;
  64761. }
  64762. this._blurKernelX = value;
  64763. this._preparePostProcesses();
  64764. },
  64765. enumerable: true,
  64766. configurable: true
  64767. });
  64768. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64769. get: function () {
  64770. return this._blurKernelY;
  64771. },
  64772. set: function (value) {
  64773. if (this._blurKernelY === value) {
  64774. return;
  64775. }
  64776. this._blurKernelY = value;
  64777. this._preparePostProcesses();
  64778. },
  64779. enumerable: true,
  64780. configurable: true
  64781. });
  64782. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64783. var engine = this.getScene().getEngine();
  64784. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64785. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64786. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64787. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64788. };
  64789. MirrorTexture.prototype._onRatioRescale = function () {
  64790. if (this._sizeRatio) {
  64791. this.resize(this._initialSizeParameter);
  64792. if (!this._adaptiveBlurKernel) {
  64793. this._preparePostProcesses();
  64794. }
  64795. }
  64796. if (this._adaptiveBlurKernel) {
  64797. this._autoComputeBlurKernel();
  64798. }
  64799. };
  64800. MirrorTexture.prototype._updateGammaSpace = function () {
  64801. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64802. };
  64803. MirrorTexture.prototype._preparePostProcesses = function () {
  64804. this.clearPostProcesses(true);
  64805. if (this._blurKernelX && this._blurKernelY) {
  64806. var engine = this.getScene().getEngine();
  64807. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64808. 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);
  64809. this._blurX.autoClear = false;
  64810. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64811. this._blurX.inputTexture = this._texture;
  64812. }
  64813. else {
  64814. this._blurX.alwaysForcePOT = true;
  64815. }
  64816. 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);
  64817. this._blurY.autoClear = false;
  64818. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64819. this.addPostProcess(this._blurX);
  64820. this.addPostProcess(this._blurY);
  64821. }
  64822. else {
  64823. if (this._blurY) {
  64824. this.removePostProcess(this._blurY);
  64825. this._blurY.dispose();
  64826. this._blurY = null;
  64827. }
  64828. if (this._blurX) {
  64829. this.removePostProcess(this._blurX);
  64830. this._blurX.dispose();
  64831. this._blurX = null;
  64832. }
  64833. }
  64834. };
  64835. MirrorTexture.prototype.clone = function () {
  64836. var scene = this.getScene();
  64837. if (!scene) {
  64838. return this;
  64839. }
  64840. var textureSize = this.getSize();
  64841. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64842. // Base texture
  64843. newTexture.hasAlpha = this.hasAlpha;
  64844. newTexture.level = this.level;
  64845. // Mirror Texture
  64846. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64847. if (this.renderList) {
  64848. newTexture.renderList = this.renderList.slice(0);
  64849. }
  64850. return newTexture;
  64851. };
  64852. MirrorTexture.prototype.serialize = function () {
  64853. if (!this.name) {
  64854. return null;
  64855. }
  64856. var serializationObject = _super.prototype.serialize.call(this);
  64857. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64858. return serializationObject;
  64859. };
  64860. MirrorTexture.prototype.dispose = function () {
  64861. _super.prototype.dispose.call(this);
  64862. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64863. };
  64864. return MirrorTexture;
  64865. }(BABYLON.RenderTargetTexture));
  64866. BABYLON.MirrorTexture = MirrorTexture;
  64867. })(BABYLON || (BABYLON = {}));
  64868. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64869. var BABYLON;
  64870. (function (BABYLON) {
  64871. /**
  64872. * Creates a refraction texture used by refraction channel of the standard material.
  64873. * @param name the texture name
  64874. * @param size size of the underlying texture
  64875. * @param scene root scene
  64876. */
  64877. var RefractionTexture = /** @class */ (function (_super) {
  64878. __extends(RefractionTexture, _super);
  64879. function RefractionTexture(name, size, scene, generateMipMaps) {
  64880. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64881. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64882. _this.depth = 2.0;
  64883. _this.onBeforeRenderObservable.add(function () {
  64884. scene.clipPlane = _this.refractionPlane;
  64885. });
  64886. _this.onAfterRenderObservable.add(function () {
  64887. delete scene.clipPlane;
  64888. });
  64889. return _this;
  64890. }
  64891. RefractionTexture.prototype.clone = function () {
  64892. var scene = this.getScene();
  64893. if (!scene) {
  64894. return this;
  64895. }
  64896. var textureSize = this.getSize();
  64897. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64898. // Base texture
  64899. newTexture.hasAlpha = this.hasAlpha;
  64900. newTexture.level = this.level;
  64901. // Refraction Texture
  64902. newTexture.refractionPlane = this.refractionPlane.clone();
  64903. if (this.renderList) {
  64904. newTexture.renderList = this.renderList.slice(0);
  64905. }
  64906. newTexture.depth = this.depth;
  64907. return newTexture;
  64908. };
  64909. RefractionTexture.prototype.serialize = function () {
  64910. if (!this.name) {
  64911. return null;
  64912. }
  64913. var serializationObject = _super.prototype.serialize.call(this);
  64914. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64915. serializationObject.depth = this.depth;
  64916. return serializationObject;
  64917. };
  64918. return RefractionTexture;
  64919. }(BABYLON.RenderTargetTexture));
  64920. BABYLON.RefractionTexture = RefractionTexture;
  64921. })(BABYLON || (BABYLON = {}));
  64922. //# sourceMappingURL=babylon.refractionTexture.js.map
  64923. var BABYLON;
  64924. (function (BABYLON) {
  64925. /**
  64926. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64927. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64928. */
  64929. var DynamicTexture = /** @class */ (function (_super) {
  64930. __extends(DynamicTexture, _super);
  64931. /**
  64932. * Creates a {BABYLON.DynamicTexture}
  64933. * @param name defines the name of the texture
  64934. * @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
  64935. * @param scene defines the scene where you want the texture
  64936. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64937. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64938. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64939. */
  64940. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64941. if (scene === void 0) { scene = null; }
  64942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64943. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64944. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64945. _this.name = name;
  64946. _this._engine = _this.getScene().getEngine();
  64947. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64948. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64949. _this._generateMipMaps = generateMipMaps;
  64950. if (options.getContext) {
  64951. _this._canvas = options;
  64952. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64953. }
  64954. else {
  64955. _this._canvas = document.createElement("canvas");
  64956. if (options.width || options.width === 0) {
  64957. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64958. }
  64959. else {
  64960. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64961. }
  64962. }
  64963. var textureSize = _this.getSize();
  64964. _this._canvas.width = textureSize.width;
  64965. _this._canvas.height = textureSize.height;
  64966. _this._context = _this._canvas.getContext("2d");
  64967. return _this;
  64968. }
  64969. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64970. /**
  64971. * Gets the current state of canRescale
  64972. */
  64973. get: function () {
  64974. return true;
  64975. },
  64976. enumerable: true,
  64977. configurable: true
  64978. });
  64979. DynamicTexture.prototype._recreate = function (textureSize) {
  64980. this._canvas.width = textureSize.width;
  64981. this._canvas.height = textureSize.height;
  64982. this.releaseInternalTexture();
  64983. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64984. };
  64985. /**
  64986. * Scales the texture
  64987. * @param ratio the scale factor to apply to both width and height
  64988. */
  64989. DynamicTexture.prototype.scale = function (ratio) {
  64990. var textureSize = this.getSize();
  64991. textureSize.width *= ratio;
  64992. textureSize.height *= ratio;
  64993. this._recreate(textureSize);
  64994. };
  64995. /**
  64996. * Resizes the texture
  64997. * @param width the new width
  64998. * @param height the new height
  64999. */
  65000. DynamicTexture.prototype.scaleTo = function (width, height) {
  65001. var textureSize = this.getSize();
  65002. textureSize.width = width;
  65003. textureSize.height = height;
  65004. this._recreate(textureSize);
  65005. };
  65006. /**
  65007. * Gets the context of the canvas used by the texture
  65008. * @returns the canvas context of the dynamic texture
  65009. */
  65010. DynamicTexture.prototype.getContext = function () {
  65011. return this._context;
  65012. };
  65013. /**
  65014. * Clears the texture
  65015. */
  65016. DynamicTexture.prototype.clear = function () {
  65017. var size = this.getSize();
  65018. this._context.fillRect(0, 0, size.width, size.height);
  65019. };
  65020. /**
  65021. * Updates the texture
  65022. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65023. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  65024. */
  65025. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  65026. if (premulAlpha === void 0) { premulAlpha = false; }
  65027. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  65028. };
  65029. /**
  65030. * Draws text onto the texture
  65031. * @param text defines the text to be drawn
  65032. * @param x defines the placement of the text from the left
  65033. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  65034. * @param font defines the font to be used with font-style, font-size, font-name
  65035. * @param color defines the color used for the text
  65036. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  65037. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  65038. * @param update defines whether texture is immediately update (default is true)
  65039. */
  65040. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  65041. if (update === void 0) { update = true; }
  65042. var size = this.getSize();
  65043. if (clearColor) {
  65044. this._context.fillStyle = clearColor;
  65045. this._context.fillRect(0, 0, size.width, size.height);
  65046. }
  65047. this._context.font = font;
  65048. if (x === null || x === undefined) {
  65049. var textSize = this._context.measureText(text);
  65050. x = (size.width - textSize.width) / 2;
  65051. }
  65052. if (y === null || y === undefined) {
  65053. var fontSize = parseInt((font.replace(/\D/g, '')));
  65054. y = (size.height / 2) + (fontSize / 3.65);
  65055. }
  65056. this._context.fillStyle = color;
  65057. this._context.fillText(text, x, y);
  65058. if (update) {
  65059. this.update(invertY);
  65060. }
  65061. };
  65062. /**
  65063. * Clones the texture
  65064. * @returns the clone of the texture.
  65065. */
  65066. DynamicTexture.prototype.clone = function () {
  65067. var scene = this.getScene();
  65068. if (!scene) {
  65069. return this;
  65070. }
  65071. var textureSize = this.getSize();
  65072. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  65073. // Base texture
  65074. newTexture.hasAlpha = this.hasAlpha;
  65075. newTexture.level = this.level;
  65076. // Dynamic Texture
  65077. newTexture.wrapU = this.wrapU;
  65078. newTexture.wrapV = this.wrapV;
  65079. return newTexture;
  65080. };
  65081. /** @hidden */
  65082. DynamicTexture.prototype._rebuild = function () {
  65083. this.update();
  65084. };
  65085. return DynamicTexture;
  65086. }(BABYLON.Texture));
  65087. BABYLON.DynamicTexture = DynamicTexture;
  65088. })(BABYLON || (BABYLON = {}));
  65089. //# sourceMappingURL=babylon.dynamicTexture.js.map
  65090. var BABYLON;
  65091. (function (BABYLON) {
  65092. var VideoTexture = /** @class */ (function (_super) {
  65093. __extends(VideoTexture, _super);
  65094. /**
  65095. * Creates a video texture.
  65096. * Sample : https://doc.babylonjs.com/how_to/video_texture
  65097. * @param {string | null} name optional name, will detect from video source, if not defined
  65098. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  65099. * @param {BABYLON.Scene} scene is obviously the current scene.
  65100. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  65101. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  65102. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  65103. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  65104. */
  65105. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  65106. if (generateMipMaps === void 0) { generateMipMaps = false; }
  65107. if (invertY === void 0) { invertY = false; }
  65108. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65109. if (settings === void 0) { settings = {
  65110. autoPlay: true,
  65111. loop: true,
  65112. autoUpdateTexture: true,
  65113. }; }
  65114. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65115. _this._onUserActionRequestedObservable = null;
  65116. _this._stillImageCaptured = false;
  65117. _this._createInternalTexture = function () {
  65118. if (_this._texture != null) {
  65119. return;
  65120. }
  65121. if (!_this._engine.needPOTTextures ||
  65122. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  65123. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65124. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65125. }
  65126. else {
  65127. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65128. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65129. _this._generateMipMaps = false;
  65130. }
  65131. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  65132. if (!_this.video.autoplay) {
  65133. var oldHandler_1 = _this.video.onplaying;
  65134. var error_1 = false;
  65135. _this.video.onplaying = function () {
  65136. _this.video.onplaying = oldHandler_1;
  65137. _this._texture.isReady = true;
  65138. _this._updateInternalTexture();
  65139. if (!error_1) {
  65140. _this.video.pause();
  65141. }
  65142. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65143. _this.onLoadObservable.notifyObservers(_this);
  65144. }
  65145. };
  65146. var playing = _this.video.play();
  65147. if (playing) {
  65148. playing.then(function () {
  65149. // Everything is good.
  65150. })
  65151. .catch(function () {
  65152. error_1 = true;
  65153. // On Chrome for instance, new policies might prevent playing without user interaction.
  65154. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  65155. _this._onUserActionRequestedObservable.notifyObservers(_this);
  65156. }
  65157. });
  65158. }
  65159. else {
  65160. _this.video.onplaying = oldHandler_1;
  65161. _this._texture.isReady = true;
  65162. _this._updateInternalTexture();
  65163. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65164. _this.onLoadObservable.notifyObservers(_this);
  65165. }
  65166. }
  65167. }
  65168. else {
  65169. _this._texture.isReady = true;
  65170. _this._updateInternalTexture();
  65171. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  65172. _this.onLoadObservable.notifyObservers(_this);
  65173. }
  65174. }
  65175. };
  65176. _this.reset = function () {
  65177. if (_this._texture == null) {
  65178. return;
  65179. }
  65180. _this._texture.dispose();
  65181. _this._texture = null;
  65182. };
  65183. _this._updateInternalTexture = function (e) {
  65184. if (_this._texture == null || !_this._texture.isReady) {
  65185. return;
  65186. }
  65187. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  65188. return;
  65189. }
  65190. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  65191. };
  65192. _this._engine = _this.getScene().getEngine();
  65193. _this._generateMipMaps = generateMipMaps;
  65194. _this._samplingMode = samplingMode;
  65195. _this.autoUpdateTexture = settings.autoUpdateTexture;
  65196. _this.name = name || _this._getName(src);
  65197. _this.video = _this._getVideo(src);
  65198. if (settings.poster) {
  65199. _this.video.poster = settings.poster;
  65200. }
  65201. if (settings.autoPlay !== undefined) {
  65202. _this.video.autoplay = settings.autoPlay;
  65203. }
  65204. if (settings.loop !== undefined) {
  65205. _this.video.loop = settings.loop;
  65206. }
  65207. _this.video.setAttribute("playsinline", "");
  65208. _this.video.addEventListener("canplay", _this._createInternalTexture);
  65209. _this.video.addEventListener("paused", _this._updateInternalTexture);
  65210. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  65211. _this.video.addEventListener("emptied", _this.reset);
  65212. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  65213. _this._createInternalTexture();
  65214. }
  65215. return _this;
  65216. }
  65217. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  65218. get: function () {
  65219. if (!this._onUserActionRequestedObservable) {
  65220. this._onUserActionRequestedObservable = new BABYLON.Observable();
  65221. }
  65222. return this._onUserActionRequestedObservable;
  65223. },
  65224. enumerable: true,
  65225. configurable: true
  65226. });
  65227. VideoTexture.prototype._getName = function (src) {
  65228. if (src instanceof HTMLVideoElement) {
  65229. return src.currentSrc;
  65230. }
  65231. if (typeof src === "object") {
  65232. return src.toString();
  65233. }
  65234. return src;
  65235. };
  65236. ;
  65237. VideoTexture.prototype._getVideo = function (src) {
  65238. if (src instanceof HTMLVideoElement) {
  65239. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  65240. return src;
  65241. }
  65242. var video = document.createElement("video");
  65243. if (typeof src === "string") {
  65244. BABYLON.Tools.SetCorsBehavior(src, video);
  65245. video.src = src;
  65246. }
  65247. else {
  65248. BABYLON.Tools.SetCorsBehavior(src[0], video);
  65249. src.forEach(function (url) {
  65250. var source = document.createElement("source");
  65251. source.src = url;
  65252. video.appendChild(source);
  65253. });
  65254. }
  65255. return video;
  65256. };
  65257. ;
  65258. /**
  65259. * Internal method to initiate `update`.
  65260. */
  65261. VideoTexture.prototype._rebuild = function () {
  65262. this.update();
  65263. };
  65264. /**
  65265. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65266. */
  65267. VideoTexture.prototype.update = function () {
  65268. if (!this.autoUpdateTexture) {
  65269. // Expecting user to call `updateTexture` manually
  65270. return;
  65271. }
  65272. this.updateTexture(true);
  65273. };
  65274. /**
  65275. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65276. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65277. */
  65278. VideoTexture.prototype.updateTexture = function (isVisible) {
  65279. if (!isVisible) {
  65280. return;
  65281. }
  65282. if (this.video.paused && this._stillImageCaptured) {
  65283. return;
  65284. }
  65285. this._stillImageCaptured = true;
  65286. this._updateInternalTexture();
  65287. };
  65288. /**
  65289. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65290. * @param url New url.
  65291. */
  65292. VideoTexture.prototype.updateURL = function (url) {
  65293. this.video.src = url;
  65294. };
  65295. VideoTexture.prototype.dispose = function () {
  65296. _super.prototype.dispose.call(this);
  65297. if (this._onUserActionRequestedObservable) {
  65298. this._onUserActionRequestedObservable.clear();
  65299. this._onUserActionRequestedObservable = null;
  65300. }
  65301. this.video.removeEventListener("canplay", this._createInternalTexture);
  65302. this.video.removeEventListener("paused", this._updateInternalTexture);
  65303. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65304. this.video.removeEventListener("emptied", this.reset);
  65305. this.video.pause();
  65306. };
  65307. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65308. var video = document.createElement("video");
  65309. video.setAttribute('autoplay', '');
  65310. video.setAttribute('muted', '');
  65311. video.setAttribute('playsinline', '');
  65312. var constraintsDeviceId;
  65313. if (constraints && constraints.deviceId) {
  65314. constraintsDeviceId = {
  65315. exact: constraints.deviceId,
  65316. };
  65317. }
  65318. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65319. if (navigator.mediaDevices) {
  65320. navigator.mediaDevices.getUserMedia({ video: constraints })
  65321. .then(function (stream) {
  65322. if (video.mozSrcObject !== undefined) {
  65323. // hack for Firefox < 19
  65324. video.mozSrcObject = stream;
  65325. }
  65326. else {
  65327. video.srcObject = stream;
  65328. }
  65329. var onPlaying = function () {
  65330. if (onReady) {
  65331. onReady(new VideoTexture("video", video, scene, true, true));
  65332. }
  65333. video.removeEventListener("playing", onPlaying);
  65334. };
  65335. video.addEventListener("playing", onPlaying);
  65336. video.play();
  65337. })
  65338. .catch(function (err) {
  65339. BABYLON.Tools.Error(err.name);
  65340. });
  65341. }
  65342. else {
  65343. navigator.getUserMedia =
  65344. navigator.getUserMedia ||
  65345. navigator.webkitGetUserMedia ||
  65346. navigator.mozGetUserMedia ||
  65347. navigator.msGetUserMedia;
  65348. if (navigator.getUserMedia) {
  65349. navigator.getUserMedia({
  65350. video: {
  65351. deviceId: constraintsDeviceId,
  65352. width: {
  65353. min: (constraints && constraints.minWidth) || 256,
  65354. max: (constraints && constraints.maxWidth) || 640,
  65355. },
  65356. height: {
  65357. min: (constraints && constraints.minHeight) || 256,
  65358. max: (constraints && constraints.maxHeight) || 480,
  65359. },
  65360. },
  65361. }, function (stream) {
  65362. if (video.mozSrcObject !== undefined) {
  65363. // hack for Firefox < 19
  65364. video.mozSrcObject = stream;
  65365. }
  65366. else {
  65367. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65368. }
  65369. video.play();
  65370. if (onReady) {
  65371. onReady(new VideoTexture("video", video, scene, true, true));
  65372. }
  65373. }, function (e) {
  65374. BABYLON.Tools.Error(e.name);
  65375. });
  65376. }
  65377. }
  65378. };
  65379. return VideoTexture;
  65380. }(BABYLON.Texture));
  65381. BABYLON.VideoTexture = VideoTexture;
  65382. })(BABYLON || (BABYLON = {}));
  65383. //# sourceMappingURL=babylon.videoTexture.js.map
  65384. var BABYLON;
  65385. (function (BABYLON) {
  65386. var RawTexture = /** @class */ (function (_super) {
  65387. __extends(RawTexture, _super);
  65388. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65389. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65390. if (invertY === void 0) { invertY = false; }
  65391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65392. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65393. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65394. _this.format = format;
  65395. _this._engine = scene.getEngine();
  65396. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65397. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65398. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65399. return _this;
  65400. }
  65401. RawTexture.prototype.update = function (data) {
  65402. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65403. };
  65404. // Statics
  65405. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65406. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65407. if (invertY === void 0) { invertY = false; }
  65408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65409. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65410. };
  65411. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65412. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65413. if (invertY === void 0) { invertY = false; }
  65414. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65415. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65416. };
  65417. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65418. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65419. if (invertY === void 0) { invertY = false; }
  65420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65421. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65422. };
  65423. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65424. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65425. if (invertY === void 0) { invertY = false; }
  65426. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65427. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65428. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65429. };
  65430. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65431. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65432. if (invertY === void 0) { invertY = false; }
  65433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65434. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65435. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65436. };
  65437. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65438. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65439. if (invertY === void 0) { invertY = false; }
  65440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65441. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65442. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65443. };
  65444. return RawTexture;
  65445. }(BABYLON.Texture));
  65446. BABYLON.RawTexture = RawTexture;
  65447. })(BABYLON || (BABYLON = {}));
  65448. //# sourceMappingURL=babylon.rawTexture.js.map
  65449. var BABYLON;
  65450. (function (BABYLON) {
  65451. /**
  65452. * Class used to store 3D textures containing user data
  65453. */
  65454. var RawTexture3D = /** @class */ (function (_super) {
  65455. __extends(RawTexture3D, _super);
  65456. /**
  65457. * Create a new RawTexture3D
  65458. * @param data defines the data of the texture
  65459. * @param width defines the width of the texture
  65460. * @param height defines the height of the texture
  65461. * @param depth defines the depth of the texture
  65462. * @param format defines the texture format to use
  65463. * @param scene defines the hosting scene
  65464. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65465. * @param invertY defines if texture must be stored with Y axis inverted
  65466. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65467. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65468. */
  65469. function RawTexture3D(data, width, height, depth,
  65470. /** Gets or sets the texture format to use */
  65471. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65472. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65473. if (invertY === void 0) { invertY = false; }
  65474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65475. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65476. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65477. _this.format = format;
  65478. _this._engine = scene.getEngine();
  65479. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65480. _this.is3D = true;
  65481. return _this;
  65482. }
  65483. /**
  65484. * Update the texture with new data
  65485. * @param data defines the data to store in the texture
  65486. */
  65487. RawTexture3D.prototype.update = function (data) {
  65488. if (!this._texture) {
  65489. return;
  65490. }
  65491. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65492. };
  65493. return RawTexture3D;
  65494. }(BABYLON.Texture));
  65495. BABYLON.RawTexture3D = RawTexture3D;
  65496. })(BABYLON || (BABYLON = {}));
  65497. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65498. var BABYLON;
  65499. (function (BABYLON) {
  65500. /**
  65501. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65502. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65503. */
  65504. var PostProcessManager = /** @class */ (function () {
  65505. /**
  65506. * Creates a new instance PostProcess
  65507. * @param scene The scene that the post process is associated with.
  65508. */
  65509. function PostProcessManager(scene) {
  65510. this._vertexBuffers = {};
  65511. this._scene = scene;
  65512. }
  65513. PostProcessManager.prototype._prepareBuffers = function () {
  65514. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65515. return;
  65516. }
  65517. // VBO
  65518. var vertices = [];
  65519. vertices.push(1, 1);
  65520. vertices.push(-1, 1);
  65521. vertices.push(-1, -1);
  65522. vertices.push(1, -1);
  65523. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65524. this._buildIndexBuffer();
  65525. };
  65526. PostProcessManager.prototype._buildIndexBuffer = function () {
  65527. // Indices
  65528. var indices = [];
  65529. indices.push(0);
  65530. indices.push(1);
  65531. indices.push(2);
  65532. indices.push(0);
  65533. indices.push(2);
  65534. indices.push(3);
  65535. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65536. };
  65537. /**
  65538. * Rebuilds the vertex buffers of the manager.
  65539. */
  65540. PostProcessManager.prototype._rebuild = function () {
  65541. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65542. if (!vb) {
  65543. return;
  65544. }
  65545. vb._rebuild();
  65546. this._buildIndexBuffer();
  65547. };
  65548. // Methods
  65549. /**
  65550. * Prepares a frame to be run through a post process.
  65551. * @param sourceTexture The input texture to the post procesess. (default: null)
  65552. * @param postProcesses An array of post processes to be run. (default: null)
  65553. * @returns True if the post processes were able to be run.
  65554. */
  65555. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65556. if (sourceTexture === void 0) { sourceTexture = null; }
  65557. if (postProcesses === void 0) { postProcesses = null; }
  65558. var camera = this._scene.activeCamera;
  65559. if (!camera) {
  65560. return false;
  65561. }
  65562. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65563. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65564. return false;
  65565. }
  65566. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65567. return true;
  65568. };
  65569. /**
  65570. * Manually render a set of post processes to a texture.
  65571. * @param postProcesses An array of post processes to be run.
  65572. * @param targetTexture The target texture to render to.
  65573. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65574. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65575. * @param lodLevel defines which lod of the texture to render to
  65576. */
  65577. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65578. if (targetTexture === void 0) { targetTexture = null; }
  65579. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65580. if (faceIndex === void 0) { faceIndex = 0; }
  65581. if (lodLevel === void 0) { lodLevel = 0; }
  65582. var engine = this._scene.getEngine();
  65583. for (var index = 0; index < postProcesses.length; index++) {
  65584. if (index < postProcesses.length - 1) {
  65585. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65586. }
  65587. else {
  65588. if (targetTexture) {
  65589. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65590. }
  65591. else {
  65592. engine.restoreDefaultFramebuffer();
  65593. }
  65594. }
  65595. var pp = postProcesses[index];
  65596. var effect = pp.apply();
  65597. if (effect) {
  65598. pp.onBeforeRenderObservable.notifyObservers(effect);
  65599. // VBOs
  65600. this._prepareBuffers();
  65601. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65602. // Draw order
  65603. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65604. pp.onAfterRenderObservable.notifyObservers(effect);
  65605. }
  65606. }
  65607. // Restore depth buffer
  65608. engine.setDepthBuffer(true);
  65609. engine.setDepthWrite(true);
  65610. };
  65611. /**
  65612. * Finalize the result of the output of the postprocesses.
  65613. * @param doNotPresent If true the result will not be displayed to the screen.
  65614. * @param targetTexture The target texture to render to.
  65615. * @param faceIndex The index of the face to bind the target texture to.
  65616. * @param postProcesses The array of post processes to render.
  65617. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65618. */
  65619. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65620. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65621. var camera = this._scene.activeCamera;
  65622. if (!camera) {
  65623. return;
  65624. }
  65625. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65626. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65627. return;
  65628. }
  65629. var engine = this._scene.getEngine();
  65630. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65631. var pp = postProcesses[index];
  65632. if (index < len - 1) {
  65633. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65634. }
  65635. else {
  65636. if (targetTexture) {
  65637. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65638. pp._outputTexture = targetTexture;
  65639. }
  65640. else {
  65641. engine.restoreDefaultFramebuffer();
  65642. pp._outputTexture = null;
  65643. }
  65644. }
  65645. if (doNotPresent) {
  65646. break;
  65647. }
  65648. var effect = pp.apply();
  65649. if (effect) {
  65650. pp.onBeforeRenderObservable.notifyObservers(effect);
  65651. // VBOs
  65652. this._prepareBuffers();
  65653. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65654. // Draw order
  65655. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65656. pp.onAfterRenderObservable.notifyObservers(effect);
  65657. }
  65658. }
  65659. // Restore states
  65660. engine.setDepthBuffer(true);
  65661. engine.setDepthWrite(true);
  65662. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65663. };
  65664. /**
  65665. * Disposes of the post process manager.
  65666. */
  65667. PostProcessManager.prototype.dispose = function () {
  65668. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65669. if (buffer) {
  65670. buffer.dispose();
  65671. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65672. }
  65673. if (this._indexBuffer) {
  65674. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65675. this._indexBuffer = null;
  65676. }
  65677. };
  65678. return PostProcessManager;
  65679. }());
  65680. BABYLON.PostProcessManager = PostProcessManager;
  65681. })(BABYLON || (BABYLON = {}));
  65682. //# sourceMappingURL=babylon.postProcessManager.js.map
  65683. var BABYLON;
  65684. (function (BABYLON) {
  65685. /**
  65686. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65687. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65688. */
  65689. var PostProcess = /** @class */ (function () {
  65690. /**
  65691. * Creates a new instance PostProcess
  65692. * @param name The name of the PostProcess.
  65693. * @param fragmentUrl The url of the fragment shader to be used.
  65694. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65695. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65696. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65697. * @param camera The camera to apply the render pass to.
  65698. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65699. * @param engine The engine which the post process will be applied. (default: current engine)
  65700. * @param reusable If the post process can be reused on the same frame. (default: false)
  65701. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65702. * @param textureType Type of textures used when performing the post process. (default: 0)
  65703. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65704. * @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
  65705. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65706. */
  65707. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65709. if (defines === void 0) { defines = null; }
  65710. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65711. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65712. if (blockCompilation === void 0) { blockCompilation = false; }
  65713. this.name = name;
  65714. /**
  65715. * Width of the texture to apply the post process on
  65716. */
  65717. this.width = -1;
  65718. /**
  65719. * Height of the texture to apply the post process on
  65720. */
  65721. this.height = -1;
  65722. /**
  65723. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65724. */
  65725. this._outputTexture = null;
  65726. /**
  65727. * If the buffer needs to be cleared before applying the post process. (default: true)
  65728. * Should be set to false if shader will overwrite all previous pixels.
  65729. */
  65730. this.autoClear = true;
  65731. /**
  65732. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65733. */
  65734. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65735. /**
  65736. * Animations to be used for the post processing
  65737. */
  65738. this.animations = new Array();
  65739. /**
  65740. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65741. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65742. */
  65743. this.enablePixelPerfectMode = false;
  65744. /**
  65745. * Force the postprocess to be applied without taking in account viewport
  65746. */
  65747. this.forceFullscreenViewport = true;
  65748. /**
  65749. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65750. *
  65751. * | Value | Type | Description |
  65752. * | ----- | ----------------------------------- | ----------- |
  65753. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65754. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65755. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65756. *
  65757. */
  65758. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65759. /**
  65760. * Force textures to be a power of two (default: false)
  65761. */
  65762. this.alwaysForcePOT = false;
  65763. /**
  65764. * Number of sample textures (default: 1)
  65765. */
  65766. this.samples = 1;
  65767. /**
  65768. * Modify the scale of the post process to be the same as the viewport (default: false)
  65769. */
  65770. this.adaptScaleToCurrentViewport = false;
  65771. this._reusable = false;
  65772. /**
  65773. * Smart array of input and output textures for the post process.
  65774. */
  65775. this._textures = new BABYLON.SmartArray(2);
  65776. /**
  65777. * The index in _textures that corresponds to the output texture.
  65778. */
  65779. this._currentRenderTextureInd = 0;
  65780. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65781. this._texelSize = BABYLON.Vector2.Zero();
  65782. // Events
  65783. /**
  65784. * An event triggered when the postprocess is activated.
  65785. */
  65786. this.onActivateObservable = new BABYLON.Observable();
  65787. /**
  65788. * An event triggered when the postprocess changes its size.
  65789. */
  65790. this.onSizeChangedObservable = new BABYLON.Observable();
  65791. /**
  65792. * An event triggered when the postprocess applies its effect.
  65793. */
  65794. this.onApplyObservable = new BABYLON.Observable();
  65795. /**
  65796. * An event triggered before rendering the postprocess
  65797. */
  65798. this.onBeforeRenderObservable = new BABYLON.Observable();
  65799. /**
  65800. * An event triggered after rendering the postprocess
  65801. */
  65802. this.onAfterRenderObservable = new BABYLON.Observable();
  65803. if (camera != null) {
  65804. this._camera = camera;
  65805. this._scene = camera.getScene();
  65806. camera.attachPostProcess(this);
  65807. this._engine = this._scene.getEngine();
  65808. this._scene.postProcesses.push(this);
  65809. }
  65810. else if (engine) {
  65811. this._engine = engine;
  65812. this._engine.postProcesses.push(this);
  65813. }
  65814. this._options = options;
  65815. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65816. this._reusable = reusable || false;
  65817. this._textureType = textureType;
  65818. this._samplers = samplers || [];
  65819. this._samplers.push("textureSampler");
  65820. this._fragmentUrl = fragmentUrl;
  65821. this._vertexUrl = vertexUrl;
  65822. this._parameters = parameters || [];
  65823. this._parameters.push("scale");
  65824. this._indexParameters = indexParameters;
  65825. if (!blockCompilation) {
  65826. this.updateEffect(defines);
  65827. }
  65828. }
  65829. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65830. /**
  65831. * A function that is added to the onActivateObservable
  65832. */
  65833. set: function (callback) {
  65834. if (this._onActivateObserver) {
  65835. this.onActivateObservable.remove(this._onActivateObserver);
  65836. }
  65837. if (callback) {
  65838. this._onActivateObserver = this.onActivateObservable.add(callback);
  65839. }
  65840. },
  65841. enumerable: true,
  65842. configurable: true
  65843. });
  65844. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65845. /**
  65846. * A function that is added to the onSizeChangedObservable
  65847. */
  65848. set: function (callback) {
  65849. if (this._onSizeChangedObserver) {
  65850. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65851. }
  65852. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65853. },
  65854. enumerable: true,
  65855. configurable: true
  65856. });
  65857. Object.defineProperty(PostProcess.prototype, "onApply", {
  65858. /**
  65859. * A function that is added to the onApplyObservable
  65860. */
  65861. set: function (callback) {
  65862. if (this._onApplyObserver) {
  65863. this.onApplyObservable.remove(this._onApplyObserver);
  65864. }
  65865. this._onApplyObserver = this.onApplyObservable.add(callback);
  65866. },
  65867. enumerable: true,
  65868. configurable: true
  65869. });
  65870. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65871. /**
  65872. * A function that is added to the onBeforeRenderObservable
  65873. */
  65874. set: function (callback) {
  65875. if (this._onBeforeRenderObserver) {
  65876. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65877. }
  65878. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65879. },
  65880. enumerable: true,
  65881. configurable: true
  65882. });
  65883. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65884. /**
  65885. * A function that is added to the onAfterRenderObservable
  65886. */
  65887. set: function (callback) {
  65888. if (this._onAfterRenderObserver) {
  65889. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65890. }
  65891. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65892. },
  65893. enumerable: true,
  65894. configurable: true
  65895. });
  65896. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65897. /**
  65898. * 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
  65899. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65900. */
  65901. get: function () {
  65902. return this._textures.data[this._currentRenderTextureInd];
  65903. },
  65904. set: function (value) {
  65905. this._forcedOutputTexture = value;
  65906. },
  65907. enumerable: true,
  65908. configurable: true
  65909. });
  65910. /**
  65911. * Gets the camera which post process is applied to.
  65912. * @returns The camera the post process is applied to.
  65913. */
  65914. PostProcess.prototype.getCamera = function () {
  65915. return this._camera;
  65916. };
  65917. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65918. /**
  65919. * Gets the texel size of the postprocess.
  65920. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65921. */
  65922. get: function () {
  65923. if (this._shareOutputWithPostProcess) {
  65924. return this._shareOutputWithPostProcess.texelSize;
  65925. }
  65926. if (this._forcedOutputTexture) {
  65927. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65928. }
  65929. return this._texelSize;
  65930. },
  65931. enumerable: true,
  65932. configurable: true
  65933. });
  65934. /**
  65935. * Gets the engine which this post process belongs to.
  65936. * @returns The engine the post process was enabled with.
  65937. */
  65938. PostProcess.prototype.getEngine = function () {
  65939. return this._engine;
  65940. };
  65941. /**
  65942. * The effect that is created when initializing the post process.
  65943. * @returns The created effect corrisponding the the postprocess.
  65944. */
  65945. PostProcess.prototype.getEffect = function () {
  65946. return this._effect;
  65947. };
  65948. /**
  65949. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65950. * @param postProcess The post process to share the output with.
  65951. * @returns This post process.
  65952. */
  65953. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65954. this._disposeTextures();
  65955. this._shareOutputWithPostProcess = postProcess;
  65956. return this;
  65957. };
  65958. /**
  65959. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65960. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65961. */
  65962. PostProcess.prototype.useOwnOutput = function () {
  65963. if (this._textures.length == 0) {
  65964. this._textures = new BABYLON.SmartArray(2);
  65965. }
  65966. this._shareOutputWithPostProcess = null;
  65967. };
  65968. /**
  65969. * Updates the effect with the current post process compile time values and recompiles the shader.
  65970. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65971. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65972. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65973. * @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
  65974. * @param onCompiled Called when the shader has been compiled.
  65975. * @param onError Called if there is an error when compiling a shader.
  65976. */
  65977. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65978. if (defines === void 0) { defines = null; }
  65979. if (uniforms === void 0) { uniforms = null; }
  65980. if (samplers === void 0) { samplers = null; }
  65981. 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);
  65982. };
  65983. /**
  65984. * The post process is reusable if it can be used multiple times within one frame.
  65985. * @returns If the post process is reusable
  65986. */
  65987. PostProcess.prototype.isReusable = function () {
  65988. return this._reusable;
  65989. };
  65990. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65991. PostProcess.prototype.markTextureDirty = function () {
  65992. this.width = -1;
  65993. };
  65994. /**
  65995. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65996. * 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.
  65997. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65998. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65999. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  66000. * @returns The target texture that was bound to be written to.
  66001. */
  66002. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  66003. var _this = this;
  66004. if (sourceTexture === void 0) { sourceTexture = null; }
  66005. camera = camera || this._camera;
  66006. var scene = camera.getScene();
  66007. var engine = scene.getEngine();
  66008. var maxSize = engine.getCaps().maxTextureSize;
  66009. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  66010. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  66011. // 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
  66012. var webVRCamera = camera.parent;
  66013. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  66014. requiredWidth /= 2;
  66015. }
  66016. var desiredWidth = (this._options.width || requiredWidth);
  66017. var desiredHeight = this._options.height || requiredHeight;
  66018. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  66019. if (this.adaptScaleToCurrentViewport) {
  66020. var currentViewport = engine.currentViewport;
  66021. if (currentViewport) {
  66022. desiredWidth *= currentViewport.width;
  66023. desiredHeight *= currentViewport.height;
  66024. }
  66025. }
  66026. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  66027. if (!this._options.width) {
  66028. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  66029. }
  66030. if (!this._options.height) {
  66031. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  66032. }
  66033. }
  66034. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  66035. if (this._textures.length > 0) {
  66036. for (var i = 0; i < this._textures.length; i++) {
  66037. this._engine._releaseTexture(this._textures.data[i]);
  66038. }
  66039. this._textures.reset();
  66040. }
  66041. this.width = desiredWidth;
  66042. this.height = desiredHeight;
  66043. var textureSize = { width: this.width, height: this.height };
  66044. var textureOptions = {
  66045. generateMipMaps: false,
  66046. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  66047. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  66048. samplingMode: this.renderTargetSamplingMode,
  66049. type: this._textureType
  66050. };
  66051. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66052. if (this._reusable) {
  66053. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  66054. }
  66055. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  66056. this.onSizeChangedObservable.notifyObservers(this);
  66057. }
  66058. this._textures.forEach(function (texture) {
  66059. if (texture.samples !== _this.samples) {
  66060. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  66061. }
  66062. });
  66063. }
  66064. var target;
  66065. if (this._shareOutputWithPostProcess) {
  66066. target = this._shareOutputWithPostProcess.inputTexture;
  66067. }
  66068. else if (this._forcedOutputTexture) {
  66069. target = this._forcedOutputTexture;
  66070. this.width = this._forcedOutputTexture.width;
  66071. this.height = this._forcedOutputTexture.height;
  66072. }
  66073. else {
  66074. target = this.inputTexture;
  66075. }
  66076. // Bind the input of this post process to be used as the output of the previous post process.
  66077. if (this.enablePixelPerfectMode) {
  66078. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  66079. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  66080. }
  66081. else {
  66082. this._scaleRatio.copyFromFloats(1, 1);
  66083. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  66084. }
  66085. this.onActivateObservable.notifyObservers(camera);
  66086. // Clear
  66087. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  66088. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  66089. }
  66090. if (this._reusable) {
  66091. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  66092. }
  66093. return target;
  66094. };
  66095. Object.defineProperty(PostProcess.prototype, "isSupported", {
  66096. /**
  66097. * If the post process is supported.
  66098. */
  66099. get: function () {
  66100. return this._effect.isSupported;
  66101. },
  66102. enumerable: true,
  66103. configurable: true
  66104. });
  66105. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  66106. /**
  66107. * The aspect ratio of the output texture.
  66108. */
  66109. get: function () {
  66110. if (this._shareOutputWithPostProcess) {
  66111. return this._shareOutputWithPostProcess.aspectRatio;
  66112. }
  66113. if (this._forcedOutputTexture) {
  66114. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  66115. }
  66116. return this.width / this.height;
  66117. },
  66118. enumerable: true,
  66119. configurable: true
  66120. });
  66121. /**
  66122. * Get a value indicating if the post-process is ready to be used
  66123. * @returns true if the post-process is ready (shader is compiled)
  66124. */
  66125. PostProcess.prototype.isReady = function () {
  66126. return this._effect && this._effect.isReady();
  66127. };
  66128. /**
  66129. * Binds all textures and uniforms to the shader, this will be run on every pass.
  66130. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  66131. */
  66132. PostProcess.prototype.apply = function () {
  66133. // Check
  66134. if (!this._effect || !this._effect.isReady())
  66135. return null;
  66136. // States
  66137. this._engine.enableEffect(this._effect);
  66138. this._engine.setState(false);
  66139. this._engine.setDepthBuffer(false);
  66140. this._engine.setDepthWrite(false);
  66141. // Alpha
  66142. this._engine.setAlphaMode(this.alphaMode);
  66143. if (this.alphaConstants) {
  66144. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  66145. }
  66146. // Bind the output texture of the preivous post process as the input to this post process.
  66147. var source;
  66148. if (this._shareOutputWithPostProcess) {
  66149. source = this._shareOutputWithPostProcess.inputTexture;
  66150. }
  66151. else if (this._forcedOutputTexture) {
  66152. source = this._forcedOutputTexture;
  66153. }
  66154. else {
  66155. source = this.inputTexture;
  66156. }
  66157. this._effect._bindTexture("textureSampler", source);
  66158. // Parameters
  66159. this._effect.setVector2("scale", this._scaleRatio);
  66160. this.onApplyObservable.notifyObservers(this._effect);
  66161. return this._effect;
  66162. };
  66163. PostProcess.prototype._disposeTextures = function () {
  66164. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  66165. return;
  66166. }
  66167. if (this._textures.length > 0) {
  66168. for (var i = 0; i < this._textures.length; i++) {
  66169. this._engine._releaseTexture(this._textures.data[i]);
  66170. }
  66171. }
  66172. this._textures.dispose();
  66173. };
  66174. /**
  66175. * Disposes the post process.
  66176. * @param camera The camera to dispose the post process on.
  66177. */
  66178. PostProcess.prototype.dispose = function (camera) {
  66179. camera = camera || this._camera;
  66180. this._disposeTextures();
  66181. if (this._scene) {
  66182. var index_1 = this._scene.postProcesses.indexOf(this);
  66183. if (index_1 !== -1) {
  66184. this._scene.postProcesses.splice(index_1, 1);
  66185. }
  66186. }
  66187. else {
  66188. var index_2 = this._engine.postProcesses.indexOf(this);
  66189. if (index_2 !== -1) {
  66190. this._engine.postProcesses.splice(index_2, 1);
  66191. }
  66192. }
  66193. if (!camera) {
  66194. return;
  66195. }
  66196. camera.detachPostProcess(this);
  66197. var index = camera._postProcesses.indexOf(this);
  66198. if (index === 0 && camera._postProcesses.length > 0) {
  66199. var firstPostProcess = this._camera._getFirstPostProcess();
  66200. if (firstPostProcess) {
  66201. firstPostProcess.markTextureDirty();
  66202. }
  66203. }
  66204. this.onActivateObservable.clear();
  66205. this.onAfterRenderObservable.clear();
  66206. this.onApplyObservable.clear();
  66207. this.onBeforeRenderObservable.clear();
  66208. this.onSizeChangedObservable.clear();
  66209. };
  66210. return PostProcess;
  66211. }());
  66212. BABYLON.PostProcess = PostProcess;
  66213. })(BABYLON || (BABYLON = {}));
  66214. //# sourceMappingURL=babylon.postProcess.js.map
  66215. var BABYLON;
  66216. (function (BABYLON) {
  66217. var PassPostProcess = /** @class */ (function (_super) {
  66218. __extends(PassPostProcess, _super);
  66219. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  66220. if (camera === void 0) { camera = null; }
  66221. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66222. if (blockCompilation === void 0) { blockCompilation = false; }
  66223. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  66224. }
  66225. return PassPostProcess;
  66226. }(BABYLON.PostProcess));
  66227. BABYLON.PassPostProcess = PassPostProcess;
  66228. })(BABYLON || (BABYLON = {}));
  66229. //# sourceMappingURL=babylon.passPostProcess.js.map
  66230. var __assign = (this && this.__assign) || Object.assign || function(t) {
  66231. for (var s, i = 1, n = arguments.length; i < n; i++) {
  66232. s = arguments[i];
  66233. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  66234. t[p] = s[p];
  66235. }
  66236. return t;
  66237. };
  66238. var BABYLON;
  66239. (function (BABYLON) {
  66240. /**
  66241. * Default implementation IShadowGenerator.
  66242. * This is the main object responsible of generating shadows in the framework.
  66243. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  66244. */
  66245. var ShadowGenerator = /** @class */ (function () {
  66246. /**
  66247. * Creates a ShadowGenerator object.
  66248. * A ShadowGenerator is the required tool to use the shadows.
  66249. * Each light casting shadows needs to use its own ShadowGenerator.
  66250. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  66251. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  66252. * @param light The light object generating the shadows.
  66253. * @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.
  66254. */
  66255. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  66256. this._bias = 0.00005;
  66257. this._normalBias = 0;
  66258. this._blurBoxOffset = 1;
  66259. this._blurScale = 2;
  66260. this._blurKernel = 1;
  66261. this._useKernelBlur = false;
  66262. this._filter = ShadowGenerator.FILTER_NONE;
  66263. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66264. this._contactHardeningLightSizeUVRatio = 0.1;
  66265. this._darkness = 0;
  66266. this._transparencyShadow = false;
  66267. /**
  66268. * Controls the extent to which the shadows fade out at the edge of the frustum
  66269. * Used only by directionals and spots
  66270. */
  66271. this.frustumEdgeFalloff = 0;
  66272. /**
  66273. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66274. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66275. * It might on the other hand introduce peter panning.
  66276. */
  66277. this.forceBackFacesOnly = false;
  66278. this._lightDirection = BABYLON.Vector3.Zero();
  66279. this._viewMatrix = BABYLON.Matrix.Zero();
  66280. this._projectionMatrix = BABYLON.Matrix.Zero();
  66281. this._transformMatrix = BABYLON.Matrix.Zero();
  66282. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66283. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66284. this._currentFaceIndex = 0;
  66285. this._currentFaceIndexCache = 0;
  66286. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66287. this._mapSize = mapSize;
  66288. this._light = light;
  66289. this._scene = light.getScene();
  66290. light._shadowGenerator = this;
  66291. // Texture type fallback from float to int if not supported.
  66292. var caps = this._scene.getEngine().getCaps();
  66293. if (!useFullFloatFirst) {
  66294. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66295. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66296. }
  66297. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66298. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66299. }
  66300. else {
  66301. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66302. }
  66303. }
  66304. else {
  66305. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66306. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66307. }
  66308. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66309. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66310. }
  66311. else {
  66312. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66313. }
  66314. }
  66315. this._initializeGenerator();
  66316. this._applyFilterValues();
  66317. }
  66318. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66319. /**
  66320. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66321. */
  66322. get: function () {
  66323. return this._bias;
  66324. },
  66325. /**
  66326. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66327. */
  66328. set: function (bias) {
  66329. this._bias = bias;
  66330. },
  66331. enumerable: true,
  66332. configurable: true
  66333. });
  66334. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66335. /**
  66336. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66337. */
  66338. get: function () {
  66339. return this._normalBias;
  66340. },
  66341. /**
  66342. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66343. */
  66344. set: function (normalBias) {
  66345. this._normalBias = normalBias;
  66346. },
  66347. enumerable: true,
  66348. configurable: true
  66349. });
  66350. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66351. /**
  66352. * Gets the blur box offset: offset applied during the blur pass.
  66353. * Only usefull if useKernelBlur = false
  66354. */
  66355. get: function () {
  66356. return this._blurBoxOffset;
  66357. },
  66358. /**
  66359. * Sets the blur box offset: offset applied during the blur pass.
  66360. * Only usefull if useKernelBlur = false
  66361. */
  66362. set: function (value) {
  66363. if (this._blurBoxOffset === value) {
  66364. return;
  66365. }
  66366. this._blurBoxOffset = value;
  66367. this._disposeBlurPostProcesses();
  66368. },
  66369. enumerable: true,
  66370. configurable: true
  66371. });
  66372. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66373. /**
  66374. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66375. * 2 means half of the size.
  66376. */
  66377. get: function () {
  66378. return this._blurScale;
  66379. },
  66380. /**
  66381. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66382. * 2 means half of the size.
  66383. */
  66384. set: function (value) {
  66385. if (this._blurScale === value) {
  66386. return;
  66387. }
  66388. this._blurScale = value;
  66389. this._disposeBlurPostProcesses();
  66390. },
  66391. enumerable: true,
  66392. configurable: true
  66393. });
  66394. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66395. /**
  66396. * Gets the blur kernel: kernel size of the blur pass.
  66397. * Only usefull if useKernelBlur = true
  66398. */
  66399. get: function () {
  66400. return this._blurKernel;
  66401. },
  66402. /**
  66403. * Sets the blur kernel: kernel size of the blur pass.
  66404. * Only usefull if useKernelBlur = true
  66405. */
  66406. set: function (value) {
  66407. if (this._blurKernel === value) {
  66408. return;
  66409. }
  66410. this._blurKernel = value;
  66411. this._disposeBlurPostProcesses();
  66412. },
  66413. enumerable: true,
  66414. configurable: true
  66415. });
  66416. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66417. /**
  66418. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66419. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66420. */
  66421. get: function () {
  66422. return this._useKernelBlur;
  66423. },
  66424. /**
  66425. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66426. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66427. */
  66428. set: function (value) {
  66429. if (this._useKernelBlur === value) {
  66430. return;
  66431. }
  66432. this._useKernelBlur = value;
  66433. this._disposeBlurPostProcesses();
  66434. },
  66435. enumerable: true,
  66436. configurable: true
  66437. });
  66438. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66439. /**
  66440. * Gets the depth scale used in ESM mode.
  66441. */
  66442. get: function () {
  66443. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66444. },
  66445. /**
  66446. * Sets the depth scale used in ESM mode.
  66447. * This can override the scale stored on the light.
  66448. */
  66449. set: function (value) {
  66450. this._depthScale = value;
  66451. },
  66452. enumerable: true,
  66453. configurable: true
  66454. });
  66455. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66456. /**
  66457. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66458. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66459. */
  66460. get: function () {
  66461. return this._filter;
  66462. },
  66463. /**
  66464. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66465. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66466. */
  66467. set: function (value) {
  66468. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66469. if (this._light.needCube()) {
  66470. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66471. this.useExponentialShadowMap = true;
  66472. return;
  66473. }
  66474. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66475. this.useCloseExponentialShadowMap = true;
  66476. return;
  66477. }
  66478. // PCF on cubemap would also be expensive
  66479. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66480. this.usePoissonSampling = true;
  66481. return;
  66482. }
  66483. }
  66484. // Weblg1 fallback for PCF.
  66485. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66486. if (this._scene.getEngine().webGLVersion === 1) {
  66487. this.usePoissonSampling = true;
  66488. return;
  66489. }
  66490. }
  66491. if (this._filter === value) {
  66492. return;
  66493. }
  66494. this._filter = value;
  66495. this._disposeBlurPostProcesses();
  66496. this._applyFilterValues();
  66497. this._light._markMeshesAsLightDirty();
  66498. },
  66499. enumerable: true,
  66500. configurable: true
  66501. });
  66502. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66503. /**
  66504. * Gets if the current filter is set to Poisson Sampling.
  66505. */
  66506. get: function () {
  66507. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66508. },
  66509. /**
  66510. * Sets the current filter to Poisson Sampling.
  66511. */
  66512. set: function (value) {
  66513. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66514. return;
  66515. }
  66516. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66517. },
  66518. enumerable: true,
  66519. configurable: true
  66520. });
  66521. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66522. /**
  66523. * Gets if the current filter is set to VSM.
  66524. * DEPRECATED. Should use useExponentialShadowMap instead.
  66525. */
  66526. get: function () {
  66527. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66528. return this.useExponentialShadowMap;
  66529. },
  66530. /**
  66531. * Sets the current filter is to VSM.
  66532. * DEPRECATED. Should use useExponentialShadowMap instead.
  66533. */
  66534. set: function (value) {
  66535. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66536. this.useExponentialShadowMap = value;
  66537. },
  66538. enumerable: true,
  66539. configurable: true
  66540. });
  66541. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66542. /**
  66543. * Gets if the current filter is set to blurred VSM.
  66544. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66545. */
  66546. get: function () {
  66547. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66548. return this.useBlurExponentialShadowMap;
  66549. },
  66550. /**
  66551. * Sets the current filter is to blurred VSM.
  66552. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66553. */
  66554. set: function (value) {
  66555. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66556. this.useBlurExponentialShadowMap = value;
  66557. },
  66558. enumerable: true,
  66559. configurable: true
  66560. });
  66561. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66562. /**
  66563. * Gets if the current filter is set to ESM.
  66564. */
  66565. get: function () {
  66566. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66567. },
  66568. /**
  66569. * Sets the current filter is to ESM.
  66570. */
  66571. set: function (value) {
  66572. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66573. return;
  66574. }
  66575. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66576. },
  66577. enumerable: true,
  66578. configurable: true
  66579. });
  66580. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66581. /**
  66582. * Gets if the current filter is set to filtered ESM.
  66583. */
  66584. get: function () {
  66585. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66586. },
  66587. /**
  66588. * Gets if the current filter is set to filtered ESM.
  66589. */
  66590. set: function (value) {
  66591. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66592. return;
  66593. }
  66594. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66595. },
  66596. enumerable: true,
  66597. configurable: true
  66598. });
  66599. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66600. /**
  66601. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66602. * exponential to prevent steep falloff artifacts).
  66603. */
  66604. get: function () {
  66605. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66606. },
  66607. /**
  66608. * Sets the current filter to "close ESM" (using the inverse of the
  66609. * exponential to prevent steep falloff artifacts).
  66610. */
  66611. set: function (value) {
  66612. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66613. return;
  66614. }
  66615. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66616. },
  66617. enumerable: true,
  66618. configurable: true
  66619. });
  66620. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66621. /**
  66622. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66623. * exponential to prevent steep falloff artifacts).
  66624. */
  66625. get: function () {
  66626. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66627. },
  66628. /**
  66629. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66630. * exponential to prevent steep falloff artifacts).
  66631. */
  66632. set: function (value) {
  66633. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66634. return;
  66635. }
  66636. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66637. },
  66638. enumerable: true,
  66639. configurable: true
  66640. });
  66641. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66642. /**
  66643. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66644. */
  66645. get: function () {
  66646. return this.filter === ShadowGenerator.FILTER_PCF;
  66647. },
  66648. /**
  66649. * Sets the current filter to "PCF" (percentage closer filtering).
  66650. */
  66651. set: function (value) {
  66652. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66653. return;
  66654. }
  66655. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66656. },
  66657. enumerable: true,
  66658. configurable: true
  66659. });
  66660. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66661. /**
  66662. * Gets the PCF or PCSS Quality.
  66663. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66664. */
  66665. get: function () {
  66666. return this._filteringQuality;
  66667. },
  66668. /**
  66669. * Sets the PCF or PCSS Quality.
  66670. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66671. */
  66672. set: function (filteringQuality) {
  66673. this._filteringQuality = filteringQuality;
  66674. },
  66675. enumerable: true,
  66676. configurable: true
  66677. });
  66678. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66679. /**
  66680. * Gets if the current filter is set to "PCSS" (contact hardening).
  66681. */
  66682. get: function () {
  66683. return this.filter === ShadowGenerator.FILTER_PCSS;
  66684. },
  66685. /**
  66686. * Sets the current filter to "PCSS" (contact hardening).
  66687. */
  66688. set: function (value) {
  66689. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66690. return;
  66691. }
  66692. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66693. },
  66694. enumerable: true,
  66695. configurable: true
  66696. });
  66697. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66698. /**
  66699. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66700. * Using a ratio helps keeping shape stability independently of the map size.
  66701. *
  66702. * It does not account for the light projection as it was having too much
  66703. * instability during the light setup or during light position changes.
  66704. *
  66705. * Only valid if useContactHardeningShadow is true.
  66706. */
  66707. get: function () {
  66708. return this._contactHardeningLightSizeUVRatio;
  66709. },
  66710. /**
  66711. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66712. * Using a ratio helps keeping shape stability independently of the map size.
  66713. *
  66714. * It does not account for the light projection as it was having too much
  66715. * instability during the light setup or during light position changes.
  66716. *
  66717. * Only valid if useContactHardeningShadow is true.
  66718. */
  66719. set: function (contactHardeningLightSizeUVRatio) {
  66720. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66721. },
  66722. enumerable: true,
  66723. configurable: true
  66724. });
  66725. /**
  66726. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66727. * 0 means strongest and 1 would means no shadow.
  66728. * @returns the darkness.
  66729. */
  66730. ShadowGenerator.prototype.getDarkness = function () {
  66731. return this._darkness;
  66732. };
  66733. /**
  66734. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66735. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66736. * @returns the shadow generator allowing fluent coding.
  66737. */
  66738. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66739. if (darkness >= 1.0)
  66740. this._darkness = 1.0;
  66741. else if (darkness <= 0.0)
  66742. this._darkness = 0.0;
  66743. else
  66744. this._darkness = darkness;
  66745. return this;
  66746. };
  66747. /**
  66748. * Sets the ability to have transparent shadow (boolean).
  66749. * @param transparent True if transparent else False
  66750. * @returns the shadow generator allowing fluent coding
  66751. */
  66752. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66753. this._transparencyShadow = transparent;
  66754. return this;
  66755. };
  66756. /**
  66757. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66758. * @returns The render target texture if present otherwise, null
  66759. */
  66760. ShadowGenerator.prototype.getShadowMap = function () {
  66761. return this._shadowMap;
  66762. };
  66763. /**
  66764. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66765. * @returns The render target texture if the shadow map is present otherwise, null
  66766. */
  66767. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66768. if (this._shadowMap2) {
  66769. return this._shadowMap2;
  66770. }
  66771. return this._shadowMap;
  66772. };
  66773. /**
  66774. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66775. * @param mesh Mesh to add
  66776. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66777. * @returns the Shadow Generator itself
  66778. */
  66779. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66780. if (includeDescendants === void 0) { includeDescendants = true; }
  66781. if (!this._shadowMap) {
  66782. return this;
  66783. }
  66784. if (!this._shadowMap.renderList) {
  66785. this._shadowMap.renderList = [];
  66786. }
  66787. this._shadowMap.renderList.push(mesh);
  66788. if (includeDescendants) {
  66789. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66790. }
  66791. return this;
  66792. var _a;
  66793. };
  66794. /**
  66795. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66796. * @param mesh Mesh to remove
  66797. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66798. * @returns the Shadow Generator itself
  66799. */
  66800. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66801. if (includeDescendants === void 0) { includeDescendants = true; }
  66802. if (!this._shadowMap || !this._shadowMap.renderList) {
  66803. return this;
  66804. }
  66805. var index = this._shadowMap.renderList.indexOf(mesh);
  66806. if (index !== -1) {
  66807. this._shadowMap.renderList.splice(index, 1);
  66808. }
  66809. if (includeDescendants) {
  66810. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66811. var child = _a[_i];
  66812. this.removeShadowCaster(child);
  66813. }
  66814. }
  66815. return this;
  66816. };
  66817. /**
  66818. * Returns the associated light object.
  66819. * @returns the light generating the shadow
  66820. */
  66821. ShadowGenerator.prototype.getLight = function () {
  66822. return this._light;
  66823. };
  66824. ShadowGenerator.prototype._initializeGenerator = function () {
  66825. this._light._markMeshesAsLightDirty();
  66826. this._initializeShadowMap();
  66827. };
  66828. ShadowGenerator.prototype._initializeShadowMap = function () {
  66829. var _this = this;
  66830. // Render target
  66831. var engine = this._scene.getEngine();
  66832. if (engine.webGLVersion > 1) {
  66833. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66834. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66835. }
  66836. else {
  66837. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66838. }
  66839. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66840. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66841. this._shadowMap.anisotropicFilteringLevel = 1;
  66842. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66843. this._shadowMap.renderParticles = false;
  66844. this._shadowMap.ignoreCameraViewport = true;
  66845. // Record Face Index before render.
  66846. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66847. _this._currentFaceIndex = faceIndex;
  66848. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66849. engine.setColorWrite(false);
  66850. }
  66851. });
  66852. // Custom render function.
  66853. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66854. // Blur if required afer render.
  66855. this._shadowMap.onAfterUnbindObservable.add(function () {
  66856. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66857. engine.setColorWrite(true);
  66858. }
  66859. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66860. return;
  66861. }
  66862. var shadowMap = _this.getShadowMapForRendering();
  66863. if (shadowMap) {
  66864. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66865. }
  66866. });
  66867. // Clear according to the chosen filter.
  66868. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66869. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66870. this._shadowMap.onClearObservable.add(function (engine) {
  66871. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66872. engine.clear(clearOne, false, true, false);
  66873. }
  66874. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66875. engine.clear(clearZero, true, true, false);
  66876. }
  66877. else {
  66878. engine.clear(clearOne, true, true, false);
  66879. }
  66880. });
  66881. };
  66882. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66883. var _this = this;
  66884. var engine = this._scene.getEngine();
  66885. var targetSize = this._mapSize / this.blurScale;
  66886. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66887. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66888. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66889. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66890. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66891. }
  66892. if (this.useKernelBlur) {
  66893. 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);
  66894. this._kernelBlurXPostprocess.width = targetSize;
  66895. this._kernelBlurXPostprocess.height = targetSize;
  66896. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66897. effect.setTexture("textureSampler", _this._shadowMap);
  66898. });
  66899. 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);
  66900. this._kernelBlurXPostprocess.autoClear = false;
  66901. this._kernelBlurYPostprocess.autoClear = false;
  66902. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66903. this._kernelBlurXPostprocess.packedFloat = true;
  66904. this._kernelBlurYPostprocess.packedFloat = true;
  66905. }
  66906. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66907. }
  66908. else {
  66909. 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);
  66910. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66911. effect.setFloat2("screenSize", targetSize, targetSize);
  66912. effect.setTexture("textureSampler", _this._shadowMap);
  66913. });
  66914. this._boxBlurPostprocess.autoClear = false;
  66915. this._blurPostProcesses = [this._boxBlurPostprocess];
  66916. }
  66917. };
  66918. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66919. var index;
  66920. var engine = this._scene.getEngine();
  66921. if (depthOnlySubMeshes.length) {
  66922. engine.setColorWrite(false);
  66923. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66924. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66925. }
  66926. engine.setColorWrite(true);
  66927. }
  66928. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66929. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66930. }
  66931. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66932. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66933. }
  66934. if (this._transparencyShadow) {
  66935. for (index = 0; index < transparentSubMeshes.length; index++) {
  66936. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66937. }
  66938. }
  66939. };
  66940. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66941. var _this = this;
  66942. var mesh = subMesh.getRenderingMesh();
  66943. var scene = this._scene;
  66944. var engine = scene.getEngine();
  66945. var material = subMesh.getMaterial();
  66946. if (!material) {
  66947. return;
  66948. }
  66949. // Culling
  66950. engine.setState(material.backFaceCulling);
  66951. // Managing instances
  66952. var batch = mesh._getInstancesRenderList(subMesh._id);
  66953. if (batch.mustReturn) {
  66954. return;
  66955. }
  66956. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66957. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66958. engine.enableEffect(this._effect);
  66959. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66960. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66961. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66962. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66963. this._effect.setVector3("lightData", this._cachedDirection);
  66964. }
  66965. else {
  66966. this._effect.setVector3("lightData", this._cachedPosition);
  66967. }
  66968. if (scene.activeCamera) {
  66969. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66970. }
  66971. // Alpha test
  66972. if (material && material.needAlphaTesting()) {
  66973. var alphaTexture = material.getAlphaTestTexture();
  66974. if (alphaTexture) {
  66975. this._effect.setTexture("diffuseSampler", alphaTexture);
  66976. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66977. }
  66978. }
  66979. // Bones
  66980. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66981. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66982. }
  66983. // Morph targets
  66984. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66985. if (this.forceBackFacesOnly) {
  66986. engine.setState(true, 0, false, true);
  66987. }
  66988. // Draw
  66989. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66990. if (this.forceBackFacesOnly) {
  66991. engine.setState(true, 0, false, false);
  66992. }
  66993. }
  66994. else {
  66995. // Need to reset refresh rate of the shadowMap
  66996. if (this._shadowMap) {
  66997. this._shadowMap.resetRefreshCounter();
  66998. }
  66999. }
  67000. };
  67001. ShadowGenerator.prototype._applyFilterValues = function () {
  67002. if (!this._shadowMap) {
  67003. return;
  67004. }
  67005. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  67006. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  67007. }
  67008. else {
  67009. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67010. }
  67011. };
  67012. /**
  67013. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67014. * @param onCompiled Callback triggered at the and of the effects compilation
  67015. * @param options Sets of optional options forcing the compilation with different modes
  67016. */
  67017. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  67018. var _this = this;
  67019. var localOptions = __assign({ useInstances: false }, options);
  67020. var shadowMap = this.getShadowMap();
  67021. if (!shadowMap) {
  67022. if (onCompiled) {
  67023. onCompiled(this);
  67024. }
  67025. return;
  67026. }
  67027. var renderList = shadowMap.renderList;
  67028. if (!renderList) {
  67029. if (onCompiled) {
  67030. onCompiled(this);
  67031. }
  67032. return;
  67033. }
  67034. var subMeshes = new Array();
  67035. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  67036. var mesh = renderList_1[_i];
  67037. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  67038. }
  67039. if (subMeshes.length === 0) {
  67040. if (onCompiled) {
  67041. onCompiled(this);
  67042. }
  67043. return;
  67044. }
  67045. var currentIndex = 0;
  67046. var checkReady = function () {
  67047. if (!_this._scene || !_this._scene.getEngine()) {
  67048. return;
  67049. }
  67050. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  67051. currentIndex++;
  67052. if (currentIndex >= subMeshes.length) {
  67053. if (onCompiled) {
  67054. onCompiled(_this);
  67055. }
  67056. return;
  67057. }
  67058. }
  67059. setTimeout(checkReady, 16);
  67060. };
  67061. checkReady();
  67062. };
  67063. /**
  67064. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  67065. * @param options Sets of optional options forcing the compilation with different modes
  67066. * @returns A promise that resolves when the compilation completes
  67067. */
  67068. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  67069. var _this = this;
  67070. return new Promise(function (resolve) {
  67071. _this.forceCompilation(function () {
  67072. resolve();
  67073. }, options);
  67074. });
  67075. };
  67076. /**
  67077. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  67078. * @param subMesh The submesh we want to render in the shadow map
  67079. * @param useInstances Defines wether will draw in the map using instances
  67080. * @returns true if ready otherwise, false
  67081. */
  67082. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  67083. var defines = [];
  67084. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67085. defines.push("#define FLOAT");
  67086. }
  67087. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67088. defines.push("#define ESM");
  67089. }
  67090. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  67091. defines.push("#define DEPTHTEXTURE");
  67092. }
  67093. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67094. var mesh = subMesh.getMesh();
  67095. var material = subMesh.getMaterial();
  67096. // Normal bias.
  67097. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  67098. attribs.push(BABYLON.VertexBuffer.NormalKind);
  67099. defines.push("#define NORMAL");
  67100. if (mesh.nonUniformScaling) {
  67101. defines.push("#define NONUNIFORMSCALING");
  67102. }
  67103. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  67104. defines.push("#define DIRECTIONINLIGHTDATA");
  67105. }
  67106. }
  67107. // Alpha test
  67108. if (material && material.needAlphaTesting()) {
  67109. var alphaTexture = material.getAlphaTestTexture();
  67110. if (alphaTexture) {
  67111. defines.push("#define ALPHATEST");
  67112. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67113. attribs.push(BABYLON.VertexBuffer.UVKind);
  67114. defines.push("#define UV1");
  67115. }
  67116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67117. if (alphaTexture.coordinatesIndex === 1) {
  67118. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67119. defines.push("#define UV2");
  67120. }
  67121. }
  67122. }
  67123. }
  67124. // Bones
  67125. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67126. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67127. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67128. if (mesh.numBoneInfluencers > 4) {
  67129. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67130. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67131. }
  67132. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67133. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67134. }
  67135. else {
  67136. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67137. }
  67138. // Morph targets
  67139. var manager = mesh.morphTargetManager;
  67140. var morphInfluencers = 0;
  67141. if (manager) {
  67142. if (manager.numInfluencers > 0) {
  67143. defines.push("#define MORPHTARGETS");
  67144. morphInfluencers = manager.numInfluencers;
  67145. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  67146. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  67147. }
  67148. }
  67149. // Instances
  67150. if (useInstances) {
  67151. defines.push("#define INSTANCES");
  67152. attribs.push("world0");
  67153. attribs.push("world1");
  67154. attribs.push("world2");
  67155. attribs.push("world3");
  67156. }
  67157. // Get correct effect
  67158. var join = defines.join("\n");
  67159. if (this._cachedDefines !== join) {
  67160. this._cachedDefines = join;
  67161. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  67162. }
  67163. if (!this._effect.isReady()) {
  67164. return false;
  67165. }
  67166. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67167. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  67168. this._initializeBlurRTTAndPostProcesses();
  67169. }
  67170. }
  67171. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  67172. return false;
  67173. }
  67174. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  67175. return false;
  67176. }
  67177. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  67178. return false;
  67179. }
  67180. return true;
  67181. };
  67182. /**
  67183. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  67184. * @param defines Defines of the material we want to update
  67185. * @param lightIndex Index of the light in the enabled light list of the material
  67186. */
  67187. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  67188. var scene = this._scene;
  67189. var light = this._light;
  67190. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67191. return;
  67192. }
  67193. defines["SHADOW" + lightIndex] = true;
  67194. if (this.useContactHardeningShadow) {
  67195. defines["SHADOWPCSS" + lightIndex] = true;
  67196. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67197. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67198. }
  67199. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67200. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67201. }
  67202. // else default to high.
  67203. }
  67204. if (this.usePercentageCloserFiltering) {
  67205. defines["SHADOWPCF" + lightIndex] = true;
  67206. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  67207. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  67208. }
  67209. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  67210. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  67211. }
  67212. // else default to high.
  67213. }
  67214. else if (this.usePoissonSampling) {
  67215. defines["SHADOWPOISSON" + lightIndex] = true;
  67216. }
  67217. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  67218. defines["SHADOWESM" + lightIndex] = true;
  67219. }
  67220. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  67221. defines["SHADOWCLOSEESM" + lightIndex] = true;
  67222. }
  67223. if (light.needCube()) {
  67224. defines["SHADOWCUBE" + lightIndex] = true;
  67225. }
  67226. };
  67227. /**
  67228. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  67229. * defined in the generator but impacting the effect).
  67230. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  67231. * @param effect The effect we are binfing the information for
  67232. */
  67233. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  67234. var light = this._light;
  67235. var scene = this._scene;
  67236. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  67237. return;
  67238. }
  67239. var camera = scene.activeCamera;
  67240. if (!camera) {
  67241. return;
  67242. }
  67243. var shadowMap = this.getShadowMap();
  67244. if (!shadowMap) {
  67245. return;
  67246. }
  67247. if (!light.needCube()) {
  67248. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  67249. }
  67250. // Only PCF uses depth stencil texture.
  67251. if (this._filter === ShadowGenerator.FILTER_PCF) {
  67252. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67253. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67254. }
  67255. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  67256. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67257. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  67258. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  67259. }
  67260. else {
  67261. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67262. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67263. }
  67264. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67265. };
  67266. /**
  67267. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67268. * (eq to shadow prjection matrix * light transform matrix)
  67269. * @returns The transform matrix used to create the shadow map
  67270. */
  67271. ShadowGenerator.prototype.getTransformMatrix = function () {
  67272. var scene = this._scene;
  67273. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67274. return this._transformMatrix;
  67275. }
  67276. this._currentRenderID = scene.getRenderId();
  67277. this._currentFaceIndexCache = this._currentFaceIndex;
  67278. var lightPosition = this._light.position;
  67279. if (this._light.computeTransformedInformation()) {
  67280. lightPosition = this._light.transformedPosition;
  67281. }
  67282. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67283. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67284. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67285. }
  67286. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67287. this._cachedPosition.copyFrom(lightPosition);
  67288. this._cachedDirection.copyFrom(this._lightDirection);
  67289. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67290. var shadowMap = this.getShadowMap();
  67291. if (shadowMap) {
  67292. var renderList = shadowMap.renderList;
  67293. if (renderList) {
  67294. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67295. }
  67296. }
  67297. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67298. }
  67299. return this._transformMatrix;
  67300. };
  67301. /**
  67302. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67303. * Cube and 2D textures for instance.
  67304. */
  67305. ShadowGenerator.prototype.recreateShadowMap = function () {
  67306. var shadowMap = this._shadowMap;
  67307. if (!shadowMap) {
  67308. return;
  67309. }
  67310. // Track render list.
  67311. var renderList = shadowMap.renderList;
  67312. // Clean up existing data.
  67313. this._disposeRTTandPostProcesses();
  67314. // Reinitializes.
  67315. this._initializeGenerator();
  67316. // Reaffect the filter to ensure a correct fallback if necessary.
  67317. this.filter = this.filter;
  67318. // Reaffect the filter.
  67319. this._applyFilterValues();
  67320. // Reaffect Render List.
  67321. this._shadowMap.renderList = renderList;
  67322. };
  67323. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67324. if (this._shadowMap2) {
  67325. this._shadowMap2.dispose();
  67326. this._shadowMap2 = null;
  67327. }
  67328. if (this._boxBlurPostprocess) {
  67329. this._boxBlurPostprocess.dispose();
  67330. this._boxBlurPostprocess = null;
  67331. }
  67332. if (this._kernelBlurXPostprocess) {
  67333. this._kernelBlurXPostprocess.dispose();
  67334. this._kernelBlurXPostprocess = null;
  67335. }
  67336. if (this._kernelBlurYPostprocess) {
  67337. this._kernelBlurYPostprocess.dispose();
  67338. this._kernelBlurYPostprocess = null;
  67339. }
  67340. this._blurPostProcesses = [];
  67341. };
  67342. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67343. if (this._shadowMap) {
  67344. this._shadowMap.dispose();
  67345. this._shadowMap = null;
  67346. }
  67347. this._disposeBlurPostProcesses();
  67348. };
  67349. /**
  67350. * Disposes the ShadowGenerator.
  67351. * Returns nothing.
  67352. */
  67353. ShadowGenerator.prototype.dispose = function () {
  67354. this._disposeRTTandPostProcesses();
  67355. if (this._light) {
  67356. this._light._shadowGenerator = null;
  67357. this._light._markMeshesAsLightDirty();
  67358. }
  67359. };
  67360. /**
  67361. * Serializes the shadow generator setup to a json object.
  67362. * @returns The serialized JSON object
  67363. */
  67364. ShadowGenerator.prototype.serialize = function () {
  67365. var serializationObject = {};
  67366. var shadowMap = this.getShadowMap();
  67367. if (!shadowMap) {
  67368. return serializationObject;
  67369. }
  67370. serializationObject.lightId = this._light.id;
  67371. serializationObject.mapSize = shadowMap.getRenderSize();
  67372. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67373. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67374. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67375. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67376. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67377. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67378. serializationObject.depthScale = this.depthScale;
  67379. serializationObject.darkness = this.getDarkness();
  67380. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67381. serializationObject.blurKernel = this.blurKernel;
  67382. serializationObject.blurScale = this.blurScale;
  67383. serializationObject.useKernelBlur = this.useKernelBlur;
  67384. serializationObject.transparencyShadow = this._transparencyShadow;
  67385. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67386. serializationObject.bias = this.bias;
  67387. serializationObject.normalBias = this.normalBias;
  67388. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67389. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67390. serializationObject.filteringQuality = this.filteringQuality;
  67391. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67392. serializationObject.renderList = [];
  67393. if (shadowMap.renderList) {
  67394. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67395. var mesh = shadowMap.renderList[meshIndex];
  67396. serializationObject.renderList.push(mesh.id);
  67397. }
  67398. }
  67399. return serializationObject;
  67400. };
  67401. /**
  67402. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67403. * @param parsedShadowGenerator The JSON object to parse
  67404. * @param scene The scene to create the shadow map for
  67405. * @returns The parsed shadow generator
  67406. */
  67407. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67408. //casting to point light, as light is missing the position attr and typescript complains.
  67409. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67410. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67411. var shadowMap = shadowGenerator.getShadowMap();
  67412. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67413. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67414. meshes.forEach(function (mesh) {
  67415. if (!shadowMap) {
  67416. return;
  67417. }
  67418. if (!shadowMap.renderList) {
  67419. shadowMap.renderList = [];
  67420. }
  67421. shadowMap.renderList.push(mesh);
  67422. });
  67423. }
  67424. if (parsedShadowGenerator.usePoissonSampling) {
  67425. shadowGenerator.usePoissonSampling = true;
  67426. }
  67427. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67428. shadowGenerator.useExponentialShadowMap = true;
  67429. }
  67430. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67431. shadowGenerator.useBlurExponentialShadowMap = true;
  67432. }
  67433. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67434. shadowGenerator.useCloseExponentialShadowMap = true;
  67435. }
  67436. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67437. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67438. }
  67439. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67440. shadowGenerator.usePercentageCloserFiltering = true;
  67441. }
  67442. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67443. shadowGenerator.useContactHardeningShadow = true;
  67444. }
  67445. if (parsedShadowGenerator.filteringQuality) {
  67446. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67447. }
  67448. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67449. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67450. }
  67451. // Backward compat
  67452. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67453. shadowGenerator.useExponentialShadowMap = true;
  67454. }
  67455. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67456. shadowGenerator.useBlurExponentialShadowMap = true;
  67457. }
  67458. if (parsedShadowGenerator.depthScale) {
  67459. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67460. }
  67461. if (parsedShadowGenerator.blurScale) {
  67462. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67463. }
  67464. if (parsedShadowGenerator.blurBoxOffset) {
  67465. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67466. }
  67467. if (parsedShadowGenerator.useKernelBlur) {
  67468. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67469. }
  67470. if (parsedShadowGenerator.blurKernel) {
  67471. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67472. }
  67473. if (parsedShadowGenerator.bias !== undefined) {
  67474. shadowGenerator.bias = parsedShadowGenerator.bias;
  67475. }
  67476. if (parsedShadowGenerator.normalBias !== undefined) {
  67477. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67478. }
  67479. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67480. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67481. }
  67482. if (parsedShadowGenerator.darkness) {
  67483. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67484. }
  67485. if (parsedShadowGenerator.transparencyShadow) {
  67486. shadowGenerator.setTransparencyShadow(true);
  67487. }
  67488. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67489. return shadowGenerator;
  67490. };
  67491. /**
  67492. * Shadow generator mode None: no filtering applied.
  67493. */
  67494. ShadowGenerator.FILTER_NONE = 0;
  67495. /**
  67496. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67497. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67498. */
  67499. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67500. /**
  67501. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67502. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67503. */
  67504. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67505. /**
  67506. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67507. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67508. */
  67509. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67510. /**
  67511. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67512. * edge artifacts on steep falloff.
  67513. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67514. */
  67515. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67516. /**
  67517. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67518. * edge artifacts on steep falloff.
  67519. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67520. */
  67521. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67522. /**
  67523. * Shadow generator mode PCF: Percentage Closer Filtering
  67524. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67525. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67526. */
  67527. ShadowGenerator.FILTER_PCF = 6;
  67528. /**
  67529. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67530. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67531. * Contact Hardening
  67532. */
  67533. ShadowGenerator.FILTER_PCSS = 7;
  67534. /**
  67535. * Reserved for PCF and PCSS
  67536. * Highest Quality.
  67537. *
  67538. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67539. *
  67540. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67541. */
  67542. ShadowGenerator.QUALITY_HIGH = 0;
  67543. /**
  67544. * Reserved for PCF and PCSS
  67545. * Good tradeoff for quality/perf cross devices
  67546. *
  67547. * Execute PCF on a 3*3 kernel.
  67548. *
  67549. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67550. */
  67551. ShadowGenerator.QUALITY_MEDIUM = 1;
  67552. /**
  67553. * Reserved for PCF and PCSS
  67554. * The lowest quality but the fastest.
  67555. *
  67556. * Execute PCF on a 1*1 kernel.
  67557. *
  67558. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67559. */
  67560. ShadowGenerator.QUALITY_LOW = 2;
  67561. return ShadowGenerator;
  67562. }());
  67563. BABYLON.ShadowGenerator = ShadowGenerator;
  67564. })(BABYLON || (BABYLON = {}));
  67565. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67566. var BABYLON;
  67567. (function (BABYLON) {
  67568. var DefaultLoadingScreen = /** @class */ (function () {
  67569. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67570. if (_loadingText === void 0) { _loadingText = ""; }
  67571. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67572. var _this = this;
  67573. this._renderingCanvas = _renderingCanvas;
  67574. this._loadingText = _loadingText;
  67575. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67576. // Resize
  67577. this._resizeLoadingUI = function () {
  67578. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67579. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67580. if (!_this._loadingDiv) {
  67581. return;
  67582. }
  67583. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67584. _this._loadingDiv.style.left = canvasRect.left + "px";
  67585. _this._loadingDiv.style.top = canvasRect.top + "px";
  67586. _this._loadingDiv.style.width = canvasRect.width + "px";
  67587. _this._loadingDiv.style.height = canvasRect.height + "px";
  67588. };
  67589. }
  67590. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67591. if (this._loadingDiv) {
  67592. // Do not add a loading screen if there is already one
  67593. return;
  67594. }
  67595. this._loadingDiv = document.createElement("div");
  67596. this._loadingDiv.id = "babylonjsLoadingDiv";
  67597. this._loadingDiv.style.opacity = "0";
  67598. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67599. this._loadingDiv.style.pointerEvents = "none";
  67600. // Loading text
  67601. this._loadingTextDiv = document.createElement("div");
  67602. this._loadingTextDiv.style.position = "absolute";
  67603. this._loadingTextDiv.style.left = "0";
  67604. this._loadingTextDiv.style.top = "50%";
  67605. this._loadingTextDiv.style.marginTop = "80px";
  67606. this._loadingTextDiv.style.width = "100%";
  67607. this._loadingTextDiv.style.height = "20px";
  67608. this._loadingTextDiv.style.fontFamily = "Arial";
  67609. this._loadingTextDiv.style.fontSize = "14px";
  67610. this._loadingTextDiv.style.color = "white";
  67611. this._loadingTextDiv.style.textAlign = "center";
  67612. this._loadingTextDiv.innerHTML = "Loading";
  67613. this._loadingDiv.appendChild(this._loadingTextDiv);
  67614. //set the predefined text
  67615. this._loadingTextDiv.innerHTML = this._loadingText;
  67616. // Generating keyframes
  67617. var style = document.createElement('style');
  67618. style.type = 'text/css';
  67619. 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 }";
  67620. style.innerHTML = keyFrames;
  67621. document.getElementsByTagName('head')[0].appendChild(style);
  67622. // Loading img
  67623. var imgBack = new Image();
  67624. 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";
  67625. imgBack.style.position = "absolute";
  67626. imgBack.style.left = "50%";
  67627. imgBack.style.top = "50%";
  67628. imgBack.style.marginLeft = "-60px";
  67629. imgBack.style.marginTop = "-60px";
  67630. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67631. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67632. imgBack.style.transformOrigin = "50% 50%";
  67633. imgBack.style.webkitTransformOrigin = "50% 50%";
  67634. this._loadingDiv.appendChild(imgBack);
  67635. this._resizeLoadingUI();
  67636. window.addEventListener("resize", this._resizeLoadingUI);
  67637. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67638. document.body.appendChild(this._loadingDiv);
  67639. this._loadingDiv.style.opacity = "1";
  67640. };
  67641. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67642. var _this = this;
  67643. if (!this._loadingDiv) {
  67644. return;
  67645. }
  67646. var onTransitionEnd = function () {
  67647. if (!_this._loadingDiv) {
  67648. return;
  67649. }
  67650. document.body.removeChild(_this._loadingDiv);
  67651. window.removeEventListener("resize", _this._resizeLoadingUI);
  67652. _this._loadingDiv = null;
  67653. };
  67654. this._loadingDiv.style.opacity = "0";
  67655. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67656. };
  67657. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67658. set: function (text) {
  67659. this._loadingText = text;
  67660. if (this._loadingTextDiv) {
  67661. this._loadingTextDiv.innerHTML = this._loadingText;
  67662. }
  67663. },
  67664. enumerable: true,
  67665. configurable: true
  67666. });
  67667. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67668. get: function () {
  67669. return this._loadingDivBackgroundColor;
  67670. },
  67671. set: function (color) {
  67672. this._loadingDivBackgroundColor = color;
  67673. if (!this._loadingDiv) {
  67674. return;
  67675. }
  67676. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67677. },
  67678. enumerable: true,
  67679. configurable: true
  67680. });
  67681. return DefaultLoadingScreen;
  67682. }());
  67683. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67684. })(BABYLON || (BABYLON = {}));
  67685. //# sourceMappingURL=babylon.loadingScreen.js.map
  67686. var BABYLON;
  67687. (function (BABYLON) {
  67688. var SceneLoaderProgressEvent = /** @class */ (function () {
  67689. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67690. this.lengthComputable = lengthComputable;
  67691. this.loaded = loaded;
  67692. this.total = total;
  67693. }
  67694. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67695. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67696. };
  67697. return SceneLoaderProgressEvent;
  67698. }());
  67699. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67700. var SceneLoader = /** @class */ (function () {
  67701. function SceneLoader() {
  67702. }
  67703. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67704. get: function () {
  67705. return 0;
  67706. },
  67707. enumerable: true,
  67708. configurable: true
  67709. });
  67710. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67711. get: function () {
  67712. return 1;
  67713. },
  67714. enumerable: true,
  67715. configurable: true
  67716. });
  67717. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67718. get: function () {
  67719. return 2;
  67720. },
  67721. enumerable: true,
  67722. configurable: true
  67723. });
  67724. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67725. get: function () {
  67726. return 3;
  67727. },
  67728. enumerable: true,
  67729. configurable: true
  67730. });
  67731. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67732. get: function () {
  67733. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67734. },
  67735. set: function (value) {
  67736. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67737. },
  67738. enumerable: true,
  67739. configurable: true
  67740. });
  67741. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67742. get: function () {
  67743. return SceneLoader._ShowLoadingScreen;
  67744. },
  67745. set: function (value) {
  67746. SceneLoader._ShowLoadingScreen = value;
  67747. },
  67748. enumerable: true,
  67749. configurable: true
  67750. });
  67751. Object.defineProperty(SceneLoader, "loggingLevel", {
  67752. get: function () {
  67753. return SceneLoader._loggingLevel;
  67754. },
  67755. set: function (value) {
  67756. SceneLoader._loggingLevel = value;
  67757. },
  67758. enumerable: true,
  67759. configurable: true
  67760. });
  67761. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67762. get: function () {
  67763. return SceneLoader._CleanBoneMatrixWeights;
  67764. },
  67765. set: function (value) {
  67766. SceneLoader._CleanBoneMatrixWeights = value;
  67767. },
  67768. enumerable: true,
  67769. configurable: true
  67770. });
  67771. SceneLoader._getDefaultPlugin = function () {
  67772. return SceneLoader._registeredPlugins[".babylon"];
  67773. };
  67774. SceneLoader._getPluginForExtension = function (extension) {
  67775. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67776. if (registeredPlugin) {
  67777. return registeredPlugin;
  67778. }
  67779. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67780. return SceneLoader._getDefaultPlugin();
  67781. };
  67782. SceneLoader._getPluginForDirectLoad = function (data) {
  67783. for (var extension in SceneLoader._registeredPlugins) {
  67784. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67785. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67786. return SceneLoader._registeredPlugins[extension];
  67787. }
  67788. }
  67789. return SceneLoader._getDefaultPlugin();
  67790. };
  67791. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67792. if (sceneFilename.name) {
  67793. sceneFilename = sceneFilename.name;
  67794. }
  67795. var queryStringPosition = sceneFilename.indexOf("?");
  67796. if (queryStringPosition !== -1) {
  67797. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67798. }
  67799. var dotPosition = sceneFilename.lastIndexOf(".");
  67800. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67801. return SceneLoader._getPluginForExtension(extension);
  67802. };
  67803. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67804. SceneLoader._getDirectLoad = function (sceneFilename) {
  67805. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67806. return sceneFilename.substr(5);
  67807. }
  67808. return null;
  67809. };
  67810. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67811. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67812. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67813. var plugin;
  67814. if (registeredPlugin.plugin.createPlugin) {
  67815. plugin = registeredPlugin.plugin.createPlugin();
  67816. }
  67817. else {
  67818. plugin = registeredPlugin.plugin;
  67819. }
  67820. var useArrayBuffer = registeredPlugin.isBinary;
  67821. var database;
  67822. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67823. var dataCallback = function (data, responseURL) {
  67824. if (scene.isDisposed) {
  67825. onError("Scene has been disposed");
  67826. return;
  67827. }
  67828. scene.database = database;
  67829. onSuccess(plugin, data, responseURL);
  67830. };
  67831. var request = null;
  67832. var pluginDisposed = false;
  67833. var onDisposeObservable = plugin.onDisposeObservable;
  67834. if (onDisposeObservable) {
  67835. onDisposeObservable.add(function () {
  67836. pluginDisposed = true;
  67837. if (request) {
  67838. request.abort();
  67839. request = null;
  67840. }
  67841. onDispose();
  67842. });
  67843. }
  67844. var manifestChecked = function () {
  67845. if (pluginDisposed) {
  67846. return;
  67847. }
  67848. var url = rootUrl + sceneFilename;
  67849. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67850. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67851. } : undefined, database, useArrayBuffer, function (request, exception) {
  67852. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67853. });
  67854. };
  67855. if (directLoad) {
  67856. dataCallback(directLoad);
  67857. return plugin;
  67858. }
  67859. if (rootUrl.indexOf("file:") === -1) {
  67860. var engine = scene.getEngine();
  67861. var canUseOfflineSupport = engine.enableOfflineSupport;
  67862. if (canUseOfflineSupport) {
  67863. // Also check for exceptions
  67864. var exceptionFound = false;
  67865. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67866. var regex = _a[_i];
  67867. if (regex.test(rootUrl + sceneFilename)) {
  67868. exceptionFound = true;
  67869. break;
  67870. }
  67871. }
  67872. canUseOfflineSupport = !exceptionFound;
  67873. }
  67874. if (canUseOfflineSupport) {
  67875. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67876. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67877. }
  67878. else {
  67879. manifestChecked();
  67880. }
  67881. }
  67882. // Loading file from disk via input file or drag'n'drop
  67883. else {
  67884. var fileOrString = sceneFilename;
  67885. if (fileOrString.name) { // File
  67886. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67887. }
  67888. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67889. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67890. }
  67891. else {
  67892. onError("Unable to find file named " + sceneFilename);
  67893. }
  67894. }
  67895. return plugin;
  67896. };
  67897. // Public functions
  67898. SceneLoader.GetPluginForExtension = function (extension) {
  67899. return SceneLoader._getPluginForExtension(extension).plugin;
  67900. };
  67901. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67902. return !!SceneLoader._registeredPlugins[extension];
  67903. };
  67904. SceneLoader.RegisterPlugin = function (plugin) {
  67905. if (typeof plugin.extensions === "string") {
  67906. var extension = plugin.extensions;
  67907. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67908. plugin: plugin,
  67909. isBinary: false
  67910. };
  67911. }
  67912. else {
  67913. var extensions = plugin.extensions;
  67914. Object.keys(extensions).forEach(function (extension) {
  67915. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67916. plugin: plugin,
  67917. isBinary: extensions[extension].isBinary
  67918. };
  67919. });
  67920. }
  67921. };
  67922. /**
  67923. * Import meshes into a scene
  67924. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67925. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67926. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67927. * @param scene the instance of BABYLON.Scene to append to
  67928. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67929. * @param onProgress a callback with a progress event for each file being loaded
  67930. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67931. * @param pluginExtension the extension used to determine the plugin
  67932. * @returns The loaded plugin
  67933. */
  67934. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67935. if (sceneFilename === void 0) { sceneFilename = ""; }
  67936. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67937. if (onSuccess === void 0) { onSuccess = null; }
  67938. if (onProgress === void 0) { onProgress = null; }
  67939. if (onError === void 0) { onError = null; }
  67940. if (pluginExtension === void 0) { pluginExtension = null; }
  67941. if (!scene) {
  67942. BABYLON.Tools.Error("No scene available to import mesh to");
  67943. return null;
  67944. }
  67945. if (!sceneFilename) {
  67946. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67947. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67948. }
  67949. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67950. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67951. return null;
  67952. }
  67953. var loadingToken = {};
  67954. scene._addPendingData(loadingToken);
  67955. var disposeHandler = function () {
  67956. scene._removePendingData(loadingToken);
  67957. };
  67958. var errorHandler = function (message, exception) {
  67959. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67960. if (onError) {
  67961. onError(scene, errorMessage, exception);
  67962. }
  67963. else {
  67964. BABYLON.Tools.Error(errorMessage);
  67965. // should the exception be thrown?
  67966. }
  67967. disposeHandler();
  67968. };
  67969. var progressHandler = onProgress ? function (event) {
  67970. try {
  67971. onProgress(event);
  67972. }
  67973. catch (e) {
  67974. errorHandler("Error in onProgress callback", e);
  67975. }
  67976. } : undefined;
  67977. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67978. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67979. if (onSuccess) {
  67980. try {
  67981. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67982. }
  67983. catch (e) {
  67984. errorHandler("Error in onSuccess callback", e);
  67985. }
  67986. }
  67987. scene._removePendingData(loadingToken);
  67988. };
  67989. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67990. if (plugin.rewriteRootURL) {
  67991. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67992. }
  67993. if (sceneFilename === "") {
  67994. if (sceneFilename === "") {
  67995. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67996. }
  67997. }
  67998. if (plugin.importMesh) {
  67999. var syncedPlugin = plugin;
  68000. var meshes = new Array();
  68001. var particleSystems = new Array();
  68002. var skeletons = new Array();
  68003. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  68004. return;
  68005. }
  68006. scene.loadingPluginName = plugin.name;
  68007. successHandler(meshes, particleSystems, skeletons, []);
  68008. }
  68009. else {
  68010. var asyncedPlugin = plugin;
  68011. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  68012. scene.loadingPluginName = plugin.name;
  68013. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  68014. }).catch(function (error) {
  68015. errorHandler(error.message, error);
  68016. });
  68017. }
  68018. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68019. };
  68020. /**
  68021. * Import meshes into a scene
  68022. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  68023. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68024. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68025. * @param scene the instance of BABYLON.Scene to append to
  68026. * @param onProgress a callback with a progress event for each file being loaded
  68027. * @param pluginExtension the extension used to determine the plugin
  68028. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  68029. */
  68030. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68031. if (sceneFilename === void 0) { sceneFilename = ""; }
  68032. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68033. if (onProgress === void 0) { onProgress = null; }
  68034. if (pluginExtension === void 0) { pluginExtension = null; }
  68035. return new Promise(function (resolve, reject) {
  68036. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  68037. resolve({
  68038. meshes: meshes,
  68039. particleSystems: particleSystems,
  68040. skeletons: skeletons,
  68041. animationGroups: animationGroups
  68042. });
  68043. }, onProgress, function (scene, message, exception) {
  68044. reject(exception || new Error(message));
  68045. }, pluginExtension);
  68046. });
  68047. };
  68048. /**
  68049. * Load a scene
  68050. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68051. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68052. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68053. * @param onSuccess a callback with the scene when import succeeds
  68054. * @param onProgress a callback with a progress event for each file being loaded
  68055. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68056. * @param pluginExtension the extension used to determine the plugin
  68057. * @returns The loaded plugin
  68058. */
  68059. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  68060. if (onSuccess === void 0) { onSuccess = null; }
  68061. if (onProgress === void 0) { onProgress = null; }
  68062. if (onError === void 0) { onError = null; }
  68063. if (pluginExtension === void 0) { pluginExtension = null; }
  68064. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  68065. };
  68066. /**
  68067. * Load a scene
  68068. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68069. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68070. * @param engine is the instance of BABYLON.Engine to use to create the scene
  68071. * @param onProgress a callback with a progress event for each file being loaded
  68072. * @param pluginExtension the extension used to determine the plugin
  68073. * @returns The loaded scene
  68074. */
  68075. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  68076. if (onProgress === void 0) { onProgress = null; }
  68077. if (pluginExtension === void 0) { pluginExtension = null; }
  68078. return new Promise(function (resolve, reject) {
  68079. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  68080. resolve(scene);
  68081. }, onProgress, function (scene, message, exception) {
  68082. reject(exception || new Error(message));
  68083. }, pluginExtension);
  68084. });
  68085. };
  68086. /**
  68087. * Append a scene
  68088. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68089. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68090. * @param scene is the instance of BABYLON.Scene to append to
  68091. * @param onSuccess a callback with the scene when import succeeds
  68092. * @param onProgress a callback with a progress event for each file being loaded
  68093. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68094. * @param pluginExtension the extension used to determine the plugin
  68095. * @returns The loaded plugin
  68096. */
  68097. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68098. if (sceneFilename === void 0) { sceneFilename = ""; }
  68099. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68100. if (onSuccess === void 0) { onSuccess = null; }
  68101. if (onProgress === void 0) { onProgress = null; }
  68102. if (onError === void 0) { onError = null; }
  68103. if (pluginExtension === void 0) { pluginExtension = null; }
  68104. if (!scene) {
  68105. BABYLON.Tools.Error("No scene available to append to");
  68106. return null;
  68107. }
  68108. if (!sceneFilename) {
  68109. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68110. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68111. }
  68112. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68113. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68114. return null;
  68115. }
  68116. if (SceneLoader.ShowLoadingScreen) {
  68117. scene.getEngine().displayLoadingUI();
  68118. }
  68119. var loadingToken = {};
  68120. scene._addPendingData(loadingToken);
  68121. var disposeHandler = function () {
  68122. scene._removePendingData(loadingToken);
  68123. scene.getEngine().hideLoadingUI();
  68124. };
  68125. var errorHandler = function (message, exception) {
  68126. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68127. if (onError) {
  68128. onError(scene, errorMessage, exception);
  68129. }
  68130. else {
  68131. BABYLON.Tools.Error(errorMessage);
  68132. // should the exception be thrown?
  68133. }
  68134. disposeHandler();
  68135. };
  68136. var progressHandler = onProgress ? function (event) {
  68137. try {
  68138. onProgress(event);
  68139. }
  68140. catch (e) {
  68141. errorHandler("Error in onProgress callback", e);
  68142. }
  68143. } : undefined;
  68144. var successHandler = function () {
  68145. if (onSuccess) {
  68146. try {
  68147. onSuccess(scene);
  68148. }
  68149. catch (e) {
  68150. errorHandler("Error in onSuccess callback", e);
  68151. }
  68152. }
  68153. scene._removePendingData(loadingToken);
  68154. };
  68155. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68156. if (sceneFilename === "") {
  68157. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  68158. }
  68159. if (plugin.load) {
  68160. var syncedPlugin = plugin;
  68161. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  68162. return;
  68163. }
  68164. scene.loadingPluginName = plugin.name;
  68165. successHandler();
  68166. }
  68167. else {
  68168. var asyncedPlugin = plugin;
  68169. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  68170. scene.loadingPluginName = plugin.name;
  68171. successHandler();
  68172. }).catch(function (error) {
  68173. errorHandler(error.message, error);
  68174. });
  68175. }
  68176. if (SceneLoader.ShowLoadingScreen) {
  68177. scene.executeWhenReady(function () {
  68178. scene.getEngine().hideLoadingUI();
  68179. });
  68180. }
  68181. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68182. };
  68183. /**
  68184. * Append a scene
  68185. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68186. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68187. * @param scene is the instance of BABYLON.Scene to append to
  68188. * @param onProgress a callback with a progress event for each file being loaded
  68189. * @param pluginExtension the extension used to determine the plugin
  68190. * @returns The given scene
  68191. */
  68192. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68193. if (sceneFilename === void 0) { sceneFilename = ""; }
  68194. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68195. if (onProgress === void 0) { onProgress = null; }
  68196. if (pluginExtension === void 0) { pluginExtension = null; }
  68197. return new Promise(function (resolve, reject) {
  68198. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  68199. resolve(scene);
  68200. }, onProgress, function (scene, message, exception) {
  68201. reject(exception || new Error(message));
  68202. }, pluginExtension);
  68203. });
  68204. };
  68205. /**
  68206. * Load a scene into an asset container
  68207. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68208. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68209. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  68210. * @param onSuccess a callback with the scene when import succeeds
  68211. * @param onProgress a callback with a progress event for each file being loaded
  68212. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  68213. * @param pluginExtension the extension used to determine the plugin
  68214. * @returns The loaded plugin
  68215. */
  68216. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  68217. if (sceneFilename === void 0) { sceneFilename = ""; }
  68218. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68219. if (onSuccess === void 0) { onSuccess = null; }
  68220. if (onProgress === void 0) { onProgress = null; }
  68221. if (onError === void 0) { onError = null; }
  68222. if (pluginExtension === void 0) { pluginExtension = null; }
  68223. if (!scene) {
  68224. BABYLON.Tools.Error("No scene available to load asset container to");
  68225. return null;
  68226. }
  68227. if (!sceneFilename) {
  68228. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  68229. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  68230. }
  68231. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  68232. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  68233. return null;
  68234. }
  68235. var loadingToken = {};
  68236. scene._addPendingData(loadingToken);
  68237. var disposeHandler = function () {
  68238. scene._removePendingData(loadingToken);
  68239. };
  68240. var errorHandler = function (message, exception) {
  68241. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  68242. if (onError) {
  68243. onError(scene, errorMessage, exception);
  68244. }
  68245. else {
  68246. BABYLON.Tools.Error(errorMessage);
  68247. // should the exception be thrown?
  68248. }
  68249. disposeHandler();
  68250. };
  68251. var progressHandler = onProgress ? function (event) {
  68252. try {
  68253. onProgress(event);
  68254. }
  68255. catch (e) {
  68256. errorHandler("Error in onProgress callback", e);
  68257. }
  68258. } : undefined;
  68259. var successHandler = function (assets) {
  68260. if (onSuccess) {
  68261. try {
  68262. onSuccess(assets);
  68263. }
  68264. catch (e) {
  68265. errorHandler("Error in onSuccess callback", e);
  68266. }
  68267. }
  68268. scene._removePendingData(loadingToken);
  68269. };
  68270. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68271. if (plugin.loadAssetContainer) {
  68272. var syncedPlugin = plugin;
  68273. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68274. if (!assetContainer) {
  68275. return;
  68276. }
  68277. scene.loadingPluginName = plugin.name;
  68278. successHandler(assetContainer);
  68279. }
  68280. else if (plugin.loadAssetContainerAsync) {
  68281. var asyncedPlugin = plugin;
  68282. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68283. scene.loadingPluginName = plugin.name;
  68284. successHandler(assetContainer);
  68285. }).catch(function (error) {
  68286. errorHandler(error.message, error);
  68287. });
  68288. }
  68289. else {
  68290. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68291. }
  68292. if (SceneLoader.ShowLoadingScreen) {
  68293. scene.executeWhenReady(function () {
  68294. scene.getEngine().hideLoadingUI();
  68295. });
  68296. }
  68297. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68298. };
  68299. /**
  68300. * Load a scene into an asset container
  68301. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68302. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68303. * @param scene is the instance of BABYLON.Scene to append to
  68304. * @param onProgress a callback with a progress event for each file being loaded
  68305. * @param pluginExtension the extension used to determine the plugin
  68306. * @returns The loaded asset container
  68307. */
  68308. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68309. if (sceneFilename === void 0) { sceneFilename = ""; }
  68310. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68311. if (onProgress === void 0) { onProgress = null; }
  68312. if (pluginExtension === void 0) { pluginExtension = null; }
  68313. return new Promise(function (resolve, reject) {
  68314. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68315. resolve(assetContainer);
  68316. }, onProgress, function (scene, message, exception) {
  68317. reject(exception || new Error(message));
  68318. }, pluginExtension);
  68319. });
  68320. };
  68321. // Flags
  68322. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68323. SceneLoader._ShowLoadingScreen = true;
  68324. SceneLoader._CleanBoneMatrixWeights = false;
  68325. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68326. // Members
  68327. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68328. SceneLoader._registeredPlugins = {};
  68329. return SceneLoader;
  68330. }());
  68331. BABYLON.SceneLoader = SceneLoader;
  68332. ;
  68333. })(BABYLON || (BABYLON = {}));
  68334. //# sourceMappingURL=babylon.sceneLoader.js.map
  68335. var BABYLON;
  68336. (function (BABYLON) {
  68337. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68338. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68339. var parsedMaterial = parsedData.materials[index];
  68340. if (parsedMaterial.id === id) {
  68341. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68342. }
  68343. }
  68344. return null;
  68345. };
  68346. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68347. for (var i in names) {
  68348. if (mesh.name === names[i]) {
  68349. hierarchyIds.push(mesh.id);
  68350. return true;
  68351. }
  68352. }
  68353. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68354. hierarchyIds.push(mesh.id);
  68355. return true;
  68356. }
  68357. return false;
  68358. };
  68359. var logOperation = function (operation, producer) {
  68360. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68361. };
  68362. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68363. if (addToScene === void 0) { addToScene = false; }
  68364. var container = new BABYLON.AssetContainer(scene);
  68365. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68366. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68367. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68368. // and avoid problems with multiple concurrent .babylon loads.
  68369. var log = "importScene has failed JSON parse";
  68370. try {
  68371. var parsedData = JSON.parse(data);
  68372. log = "";
  68373. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68374. var index;
  68375. var cache;
  68376. // Lights
  68377. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68378. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68379. var parsedLight = parsedData.lights[index];
  68380. var light = BABYLON.Light.Parse(parsedLight, scene);
  68381. if (light) {
  68382. container.lights.push(light);
  68383. log += (index === 0 ? "\n\tLights:" : "");
  68384. log += "\n\t\t" + light.toString(fullDetails);
  68385. }
  68386. }
  68387. }
  68388. // Animations
  68389. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68390. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68391. var parsedAnimation = parsedData.animations[index];
  68392. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68393. scene.animations.push(animation);
  68394. container.animations.push(animation);
  68395. log += (index === 0 ? "\n\tAnimations:" : "");
  68396. log += "\n\t\t" + animation.toString(fullDetails);
  68397. }
  68398. }
  68399. // Materials
  68400. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68401. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68402. var parsedMaterial = parsedData.materials[index];
  68403. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68404. container.materials.push(mat);
  68405. log += (index === 0 ? "\n\tMaterials:" : "");
  68406. log += "\n\t\t" + mat.toString(fullDetails);
  68407. }
  68408. }
  68409. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68410. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68411. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68412. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68413. container.multiMaterials.push(mmat);
  68414. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68415. log += "\n\t\t" + mmat.toString(fullDetails);
  68416. }
  68417. }
  68418. // Morph targets
  68419. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68420. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68421. var managerData = _a[_i];
  68422. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68423. }
  68424. }
  68425. // Skeletons
  68426. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68427. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68428. var parsedSkeleton = parsedData.skeletons[index];
  68429. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68430. container.skeletons.push(skeleton);
  68431. log += (index === 0 ? "\n\tSkeletons:" : "");
  68432. log += "\n\t\t" + skeleton.toString(fullDetails);
  68433. }
  68434. }
  68435. // Geometries
  68436. var geometries = parsedData.geometries;
  68437. if (geometries !== undefined && geometries !== null) {
  68438. var addedGeometry = new Array();
  68439. // Boxes
  68440. var boxes = geometries.boxes;
  68441. if (boxes !== undefined && boxes !== null) {
  68442. for (index = 0, cache = boxes.length; index < cache; index++) {
  68443. var parsedBox = boxes[index];
  68444. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68445. }
  68446. }
  68447. // Spheres
  68448. var spheres = geometries.spheres;
  68449. if (spheres !== undefined && spheres !== null) {
  68450. for (index = 0, cache = spheres.length; index < cache; index++) {
  68451. var parsedSphere = spheres[index];
  68452. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68453. }
  68454. }
  68455. // Cylinders
  68456. var cylinders = geometries.cylinders;
  68457. if (cylinders !== undefined && cylinders !== null) {
  68458. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68459. var parsedCylinder = cylinders[index];
  68460. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68461. }
  68462. }
  68463. // Toruses
  68464. var toruses = geometries.toruses;
  68465. if (toruses !== undefined && toruses !== null) {
  68466. for (index = 0, cache = toruses.length; index < cache; index++) {
  68467. var parsedTorus = toruses[index];
  68468. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68469. }
  68470. }
  68471. // Grounds
  68472. var grounds = geometries.grounds;
  68473. if (grounds !== undefined && grounds !== null) {
  68474. for (index = 0, cache = grounds.length; index < cache; index++) {
  68475. var parsedGround = grounds[index];
  68476. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68477. }
  68478. }
  68479. // Planes
  68480. var planes = geometries.planes;
  68481. if (planes !== undefined && planes !== null) {
  68482. for (index = 0, cache = planes.length; index < cache; index++) {
  68483. var parsedPlane = planes[index];
  68484. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68485. }
  68486. }
  68487. // TorusKnots
  68488. var torusKnots = geometries.torusKnots;
  68489. if (torusKnots !== undefined && torusKnots !== null) {
  68490. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68491. var parsedTorusKnot = torusKnots[index];
  68492. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68493. }
  68494. }
  68495. // VertexData
  68496. var vertexData = geometries.vertexData;
  68497. if (vertexData !== undefined && vertexData !== null) {
  68498. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68499. var parsedVertexData = vertexData[index];
  68500. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68501. }
  68502. }
  68503. addedGeometry.forEach(function (g) {
  68504. if (g) {
  68505. container.geometries.push(g);
  68506. }
  68507. });
  68508. }
  68509. // Transform nodes
  68510. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68511. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68512. var parsedTransformNode = parsedData.transformNodes[index];
  68513. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68514. container.transformNodes.push(node);
  68515. }
  68516. }
  68517. // Meshes
  68518. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68519. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68520. var parsedMesh = parsedData.meshes[index];
  68521. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68522. container.meshes.push(mesh);
  68523. log += (index === 0 ? "\n\tMeshes:" : "");
  68524. log += "\n\t\t" + mesh.toString(fullDetails);
  68525. }
  68526. }
  68527. // Cameras
  68528. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68529. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68530. var parsedCamera = parsedData.cameras[index];
  68531. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68532. container.cameras.push(camera);
  68533. log += (index === 0 ? "\n\tCameras:" : "");
  68534. log += "\n\t\t" + camera.toString(fullDetails);
  68535. }
  68536. }
  68537. // Browsing all the graph to connect the dots
  68538. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68539. var camera = scene.cameras[index];
  68540. if (camera._waitingParentId) {
  68541. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68542. camera._waitingParentId = null;
  68543. }
  68544. }
  68545. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68546. var light_1 = scene.lights[index];
  68547. if (light_1 && light_1._waitingParentId) {
  68548. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68549. light_1._waitingParentId = null;
  68550. }
  68551. }
  68552. // Sounds
  68553. // TODO: add sound
  68554. var loadedSounds = [];
  68555. var loadedSound;
  68556. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68557. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68558. var parsedSound = parsedData.sounds[index];
  68559. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68560. if (!parsedSound.url)
  68561. parsedSound.url = parsedSound.name;
  68562. if (!loadedSounds[parsedSound.url]) {
  68563. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68564. loadedSounds[parsedSound.url] = loadedSound;
  68565. container.sounds.push(loadedSound);
  68566. }
  68567. else {
  68568. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68569. }
  68570. }
  68571. else {
  68572. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68573. }
  68574. }
  68575. }
  68576. loadedSounds = [];
  68577. // Connect parents & children and parse actions
  68578. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68579. var transformNode = scene.transformNodes[index];
  68580. if (transformNode._waitingParentId) {
  68581. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68582. transformNode._waitingParentId = null;
  68583. }
  68584. }
  68585. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68586. var mesh = scene.meshes[index];
  68587. if (mesh._waitingParentId) {
  68588. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68589. mesh._waitingParentId = null;
  68590. }
  68591. if (mesh._waitingActions) {
  68592. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68593. mesh._waitingActions = null;
  68594. }
  68595. }
  68596. // freeze world matrix application
  68597. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68598. var currentMesh = scene.meshes[index];
  68599. if (currentMesh._waitingFreezeWorldMatrix) {
  68600. currentMesh.freezeWorldMatrix();
  68601. currentMesh._waitingFreezeWorldMatrix = null;
  68602. }
  68603. else {
  68604. currentMesh.computeWorldMatrix(true);
  68605. }
  68606. }
  68607. // Shadows
  68608. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68609. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68610. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68611. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68612. // SG would be available on their associated lights
  68613. }
  68614. }
  68615. // Lights exclusions / inclusions
  68616. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68617. var light_2 = scene.lights[index];
  68618. // Excluded check
  68619. if (light_2._excludedMeshesIds.length > 0) {
  68620. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68621. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68622. if (excludedMesh) {
  68623. light_2.excludedMeshes.push(excludedMesh);
  68624. }
  68625. }
  68626. light_2._excludedMeshesIds = [];
  68627. }
  68628. // Included check
  68629. if (light_2._includedOnlyMeshesIds.length > 0) {
  68630. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68631. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68632. if (includedOnlyMesh) {
  68633. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68634. }
  68635. }
  68636. light_2._includedOnlyMeshesIds = [];
  68637. }
  68638. }
  68639. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68640. // Actions (scene)
  68641. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68642. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68643. }
  68644. if (!addToScene) {
  68645. container.removeAllFromScene();
  68646. }
  68647. }
  68648. catch (err) {
  68649. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68650. if (onError) {
  68651. onError(msg, err);
  68652. }
  68653. else {
  68654. BABYLON.Tools.Log(msg);
  68655. throw err;
  68656. }
  68657. }
  68658. finally {
  68659. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68660. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68661. }
  68662. }
  68663. return container;
  68664. };
  68665. BABYLON.SceneLoader.RegisterPlugin({
  68666. name: "babylon.js",
  68667. extensions: ".babylon",
  68668. canDirectLoad: function (data) {
  68669. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68670. return true;
  68671. }
  68672. return false;
  68673. },
  68674. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68675. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68676. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68677. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68678. // and avoid problems with multiple concurrent .babylon loads.
  68679. var log = "importMesh has failed JSON parse";
  68680. try {
  68681. var parsedData = JSON.parse(data);
  68682. log = "";
  68683. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68684. if (!meshesNames) {
  68685. meshesNames = null;
  68686. }
  68687. else if (!Array.isArray(meshesNames)) {
  68688. meshesNames = [meshesNames];
  68689. }
  68690. var hierarchyIds = new Array();
  68691. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68692. var loadedSkeletonsIds = [];
  68693. var loadedMaterialsIds = [];
  68694. var index;
  68695. var cache;
  68696. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68697. var parsedMesh = parsedData.meshes[index];
  68698. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68699. if (meshesNames !== null) {
  68700. // Remove found mesh name from list.
  68701. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68702. }
  68703. //Geometry?
  68704. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68705. //does the file contain geometries?
  68706. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68707. //find the correct geometry and add it to the scene
  68708. var found = false;
  68709. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68710. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68711. return;
  68712. }
  68713. else {
  68714. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68715. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68716. switch (geometryType) {
  68717. case "boxes":
  68718. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68719. break;
  68720. case "spheres":
  68721. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68722. break;
  68723. case "cylinders":
  68724. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68725. break;
  68726. case "toruses":
  68727. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68728. break;
  68729. case "grounds":
  68730. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68731. break;
  68732. case "planes":
  68733. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68734. break;
  68735. case "torusKnots":
  68736. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68737. break;
  68738. case "vertexData":
  68739. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68740. break;
  68741. }
  68742. found = true;
  68743. }
  68744. });
  68745. }
  68746. });
  68747. if (found === false) {
  68748. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68749. }
  68750. }
  68751. }
  68752. // Material ?
  68753. if (parsedMesh.materialId) {
  68754. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68755. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68756. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68757. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68758. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68759. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68760. var subMatId = parsedMultiMaterial.materials[matIndex];
  68761. loadedMaterialsIds.push(subMatId);
  68762. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68763. if (mat) {
  68764. log += "\n\tMaterial " + mat.toString(fullDetails);
  68765. }
  68766. }
  68767. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68768. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68769. if (mmat) {
  68770. materialFound = true;
  68771. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68772. }
  68773. break;
  68774. }
  68775. }
  68776. }
  68777. if (materialFound === false) {
  68778. loadedMaterialsIds.push(parsedMesh.materialId);
  68779. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68780. if (!mat) {
  68781. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68782. }
  68783. else {
  68784. log += "\n\tMaterial " + mat.toString(fullDetails);
  68785. }
  68786. }
  68787. }
  68788. // Skeleton ?
  68789. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68790. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68791. if (skeletonAlreadyLoaded === false) {
  68792. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68793. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68794. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68795. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68796. skeletons.push(skeleton);
  68797. loadedSkeletonsIds.push(parsedSkeleton.id);
  68798. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68799. }
  68800. }
  68801. }
  68802. }
  68803. // Morph targets ?
  68804. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68805. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68806. var managerData = _a[_i];
  68807. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68808. }
  68809. }
  68810. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68811. meshes.push(mesh);
  68812. log += "\n\tMesh " + mesh.toString(fullDetails);
  68813. }
  68814. }
  68815. // Connecting parents
  68816. var currentMesh;
  68817. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68818. currentMesh = scene.meshes[index];
  68819. if (currentMesh._waitingParentId) {
  68820. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68821. currentMesh._waitingParentId = null;
  68822. }
  68823. }
  68824. // freeze and compute world matrix application
  68825. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68826. currentMesh = scene.meshes[index];
  68827. if (currentMesh._waitingFreezeWorldMatrix) {
  68828. currentMesh.freezeWorldMatrix();
  68829. currentMesh._waitingFreezeWorldMatrix = null;
  68830. }
  68831. else {
  68832. currentMesh.computeWorldMatrix(true);
  68833. }
  68834. }
  68835. }
  68836. // Particles
  68837. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68838. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68839. var parsedParticleSystem = parsedData.particleSystems[index];
  68840. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68841. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68842. }
  68843. }
  68844. }
  68845. return true;
  68846. }
  68847. catch (err) {
  68848. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68849. if (onError) {
  68850. onError(msg, err);
  68851. }
  68852. else {
  68853. BABYLON.Tools.Log(msg);
  68854. throw err;
  68855. }
  68856. }
  68857. finally {
  68858. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68859. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68860. }
  68861. }
  68862. return false;
  68863. },
  68864. load: function (scene, data, rootUrl, onError) {
  68865. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68866. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68867. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68868. // and avoid problems with multiple concurrent .babylon loads.
  68869. var log = "importScene has failed JSON parse";
  68870. try {
  68871. var parsedData = JSON.parse(data);
  68872. log = "";
  68873. // Scene
  68874. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68875. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68876. }
  68877. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68878. scene.autoClear = parsedData.autoClear;
  68879. }
  68880. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68881. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68882. }
  68883. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68884. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68885. }
  68886. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68887. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68888. }
  68889. // Fog
  68890. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68891. scene.fogMode = parsedData.fogMode;
  68892. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68893. scene.fogStart = parsedData.fogStart;
  68894. scene.fogEnd = parsedData.fogEnd;
  68895. scene.fogDensity = parsedData.fogDensity;
  68896. log += "\tFog mode for scene: ";
  68897. switch (scene.fogMode) {
  68898. // getters not compiling, so using hardcoded
  68899. case 1:
  68900. log += "exp\n";
  68901. break;
  68902. case 2:
  68903. log += "exp2\n";
  68904. break;
  68905. case 3:
  68906. log += "linear\n";
  68907. break;
  68908. }
  68909. }
  68910. //Physics
  68911. if (parsedData.physicsEnabled) {
  68912. var physicsPlugin;
  68913. if (parsedData.physicsEngine === "cannon") {
  68914. physicsPlugin = new BABYLON.CannonJSPlugin();
  68915. }
  68916. else if (parsedData.physicsEngine === "oimo") {
  68917. physicsPlugin = new BABYLON.OimoJSPlugin();
  68918. }
  68919. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68920. //else - default engine, which is currently oimo
  68921. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68922. scene.enablePhysics(physicsGravity, physicsPlugin);
  68923. }
  68924. // Metadata
  68925. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68926. scene.metadata = parsedData.metadata;
  68927. }
  68928. //collisions, if defined. otherwise, default is true
  68929. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68930. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68931. }
  68932. scene.workerCollisions = !!parsedData.workerCollisions;
  68933. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68934. if (!container) {
  68935. return false;
  68936. }
  68937. if (parsedData.autoAnimate) {
  68938. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68939. }
  68940. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68941. scene.setActiveCameraByID(parsedData.activeCameraID);
  68942. }
  68943. // Environment texture
  68944. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68945. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68946. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68947. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68948. if (parsedData.environmentTextureRotationY) {
  68949. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68950. }
  68951. scene.environmentTexture = hdrTexture;
  68952. }
  68953. else {
  68954. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68955. if (parsedData.environmentTextureRotationY) {
  68956. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68957. }
  68958. scene.environmentTexture = cubeTexture;
  68959. }
  68960. if (parsedData.createDefaultSkybox === true) {
  68961. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68962. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68963. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68964. }
  68965. }
  68966. // Finish
  68967. return true;
  68968. }
  68969. catch (err) {
  68970. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68971. if (onError) {
  68972. onError(msg, err);
  68973. }
  68974. else {
  68975. BABYLON.Tools.Log(msg);
  68976. throw err;
  68977. }
  68978. }
  68979. finally {
  68980. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68981. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68982. }
  68983. }
  68984. return false;
  68985. },
  68986. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68987. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68988. return container;
  68989. }
  68990. });
  68991. })(BABYLON || (BABYLON = {}));
  68992. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68993. var BABYLON;
  68994. (function (BABYLON) {
  68995. var FilesInput = /** @class */ (function () {
  68996. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68997. this.onProcessFileCallback = function () { return true; };
  68998. this._engine = engine;
  68999. this._currentScene = scene;
  69000. this._sceneLoadedCallback = sceneLoadedCallback;
  69001. this._progressCallback = progressCallback;
  69002. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  69003. this._textureLoadingCallback = textureLoadingCallback;
  69004. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  69005. this._onReloadCallback = onReloadCallback;
  69006. this._errorCallback = errorCallback;
  69007. }
  69008. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  69009. var _this = this;
  69010. if (elementToMonitor) {
  69011. this._elementToMonitor = elementToMonitor;
  69012. this._dragEnterHandler = function (e) { _this.drag(e); };
  69013. this._dragOverHandler = function (e) { _this.drag(e); };
  69014. this._dropHandler = function (e) { _this.drop(e); };
  69015. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  69016. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  69017. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  69018. }
  69019. };
  69020. FilesInput.prototype.dispose = function () {
  69021. if (!this._elementToMonitor) {
  69022. return;
  69023. }
  69024. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  69025. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  69026. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  69027. };
  69028. FilesInput.prototype.renderFunction = function () {
  69029. if (this._additionalRenderLoopLogicCallback) {
  69030. this._additionalRenderLoopLogicCallback();
  69031. }
  69032. if (this._currentScene) {
  69033. if (this._textureLoadingCallback) {
  69034. var remaining = this._currentScene.getWaitingItemsCount();
  69035. if (remaining > 0) {
  69036. this._textureLoadingCallback(remaining);
  69037. }
  69038. }
  69039. this._currentScene.render();
  69040. }
  69041. };
  69042. FilesInput.prototype.drag = function (e) {
  69043. e.stopPropagation();
  69044. e.preventDefault();
  69045. };
  69046. FilesInput.prototype.drop = function (eventDrop) {
  69047. eventDrop.stopPropagation();
  69048. eventDrop.preventDefault();
  69049. this.loadFiles(eventDrop);
  69050. };
  69051. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  69052. var _this = this;
  69053. var reader = folder.createReader();
  69054. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  69055. reader.readEntries(function (entries) {
  69056. remaining.count += entries.length;
  69057. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  69058. var entry = entries_1[_i];
  69059. if (entry.isFile) {
  69060. entry.file(function (file) {
  69061. file.correctName = relativePath + file.name;
  69062. files.push(file);
  69063. if (--remaining.count === 0) {
  69064. callback();
  69065. }
  69066. });
  69067. }
  69068. else if (entry.isDirectory) {
  69069. _this._traverseFolder(entry, files, remaining, callback);
  69070. }
  69071. }
  69072. if (--remaining.count) {
  69073. callback();
  69074. }
  69075. });
  69076. };
  69077. FilesInput.prototype._processFiles = function (files) {
  69078. for (var i = 0; i < files.length; i++) {
  69079. var name = files[i].correctName.toLowerCase();
  69080. var extension = name.split('.').pop();
  69081. if (!this.onProcessFileCallback(files[i], name, extension)) {
  69082. continue;
  69083. }
  69084. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  69085. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  69086. this._sceneFileToLoad = files[i];
  69087. }
  69088. else {
  69089. FilesInput.FilesToLoad[name] = files[i];
  69090. }
  69091. }
  69092. };
  69093. FilesInput.prototype.loadFiles = function (event) {
  69094. var _this = this;
  69095. if (this._startingProcessingFilesCallback)
  69096. this._startingProcessingFilesCallback();
  69097. // Handling data transfer via drag'n'drop
  69098. if (event && event.dataTransfer && event.dataTransfer.files) {
  69099. this._filesToLoad = event.dataTransfer.files;
  69100. }
  69101. // Handling files from input files
  69102. if (event && event.target && event.target.files) {
  69103. this._filesToLoad = event.target.files;
  69104. }
  69105. if (this._filesToLoad && this._filesToLoad.length > 0) {
  69106. var files_1 = new Array();
  69107. var folders = [];
  69108. var items = event.dataTransfer ? event.dataTransfer.items : null;
  69109. for (var i = 0; i < this._filesToLoad.length; i++) {
  69110. var fileToLoad = this._filesToLoad[i];
  69111. var name_1 = fileToLoad.name.toLowerCase();
  69112. var entry = void 0;
  69113. fileToLoad.correctName = name_1;
  69114. if (items) {
  69115. var item = items[i];
  69116. if (item.getAsEntry) {
  69117. entry = item.getAsEntry();
  69118. }
  69119. else if (item.webkitGetAsEntry) {
  69120. entry = item.webkitGetAsEntry();
  69121. }
  69122. }
  69123. if (!entry) {
  69124. files_1.push(fileToLoad);
  69125. }
  69126. else {
  69127. if (entry.isDirectory) {
  69128. folders.push(entry);
  69129. }
  69130. else {
  69131. files_1.push(fileToLoad);
  69132. }
  69133. }
  69134. }
  69135. if (folders.length === 0) {
  69136. this._processFiles(files_1);
  69137. this._processReload();
  69138. }
  69139. else {
  69140. var remaining = { count: folders.length };
  69141. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  69142. var folder = folders_1[_i];
  69143. this._traverseFolder(folder, files_1, remaining, function () {
  69144. _this._processFiles(files_1);
  69145. if (remaining.count === 0) {
  69146. _this._processReload();
  69147. }
  69148. });
  69149. }
  69150. }
  69151. }
  69152. };
  69153. FilesInput.prototype._processReload = function () {
  69154. if (this._onReloadCallback) {
  69155. this._onReloadCallback(this._sceneFileToLoad);
  69156. }
  69157. else {
  69158. this.reload();
  69159. }
  69160. };
  69161. FilesInput.prototype.reload = function () {
  69162. var _this = this;
  69163. // If a scene file has been provided
  69164. if (this._sceneFileToLoad) {
  69165. if (this._currentScene) {
  69166. if (BABYLON.Tools.errorsCount > 0) {
  69167. BABYLON.Tools.ClearLogCache();
  69168. }
  69169. this._engine.stopRenderLoop();
  69170. }
  69171. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  69172. if (_this._progressCallback) {
  69173. _this._progressCallback(progress);
  69174. }
  69175. }).then(function (scene) {
  69176. if (_this._currentScene) {
  69177. _this._currentScene.dispose();
  69178. }
  69179. _this._currentScene = scene;
  69180. if (_this._sceneLoadedCallback) {
  69181. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  69182. }
  69183. // Wait for textures and shaders to be ready
  69184. _this._currentScene.executeWhenReady(function () {
  69185. _this._engine.runRenderLoop(function () {
  69186. _this.renderFunction();
  69187. });
  69188. });
  69189. }).catch(function (error) {
  69190. if (_this._errorCallback) {
  69191. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  69192. }
  69193. });
  69194. }
  69195. else {
  69196. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  69197. }
  69198. };
  69199. FilesInput.FilesToLoad = {};
  69200. return FilesInput;
  69201. }());
  69202. BABYLON.FilesInput = FilesInput;
  69203. })(BABYLON || (BABYLON = {}));
  69204. //# sourceMappingURL=babylon.filesInput.js.map
  69205. var BABYLON;
  69206. (function (BABYLON) {
  69207. /**
  69208. * This class implement a typical dictionary using a string as key and the generic type T as value.
  69209. * The underlying implementation relies on an associative array to ensure the best performances.
  69210. * The value can be anything including 'null' but except 'undefined'
  69211. */
  69212. var StringDictionary = /** @class */ (function () {
  69213. function StringDictionary() {
  69214. this._count = 0;
  69215. this._data = {};
  69216. }
  69217. /**
  69218. * This will clear this dictionary and copy the content from the 'source' one.
  69219. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  69220. * @param source the dictionary to take the content from and copy to this dictionary
  69221. */
  69222. StringDictionary.prototype.copyFrom = function (source) {
  69223. var _this = this;
  69224. this.clear();
  69225. source.forEach(function (t, v) { return _this.add(t, v); });
  69226. };
  69227. /**
  69228. * Get a value based from its key
  69229. * @param key the given key to get the matching value from
  69230. * @return the value if found, otherwise undefined is returned
  69231. */
  69232. StringDictionary.prototype.get = function (key) {
  69233. var val = this._data[key];
  69234. if (val !== undefined) {
  69235. return val;
  69236. }
  69237. return undefined;
  69238. };
  69239. /**
  69240. * Get a value from its key or add it if it doesn't exist.
  69241. * This method will ensure you that a given key/data will be present in the dictionary.
  69242. * @param key the given key to get the matching value from
  69243. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69244. * The factory will only be invoked if there's no data for the given key.
  69245. * @return the value corresponding to the key.
  69246. */
  69247. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69248. var val = this.get(key);
  69249. if (val !== undefined) {
  69250. return val;
  69251. }
  69252. val = factory(key);
  69253. if (val) {
  69254. this.add(key, val);
  69255. }
  69256. return val;
  69257. };
  69258. /**
  69259. * Get a value from its key if present in the dictionary otherwise add it
  69260. * @param key the key to get the value from
  69261. * @param val if there's no such key/value pair in the dictionary add it with this value
  69262. * @return the value corresponding to the key
  69263. */
  69264. StringDictionary.prototype.getOrAdd = function (key, val) {
  69265. var curVal = this.get(key);
  69266. if (curVal !== undefined) {
  69267. return curVal;
  69268. }
  69269. this.add(key, val);
  69270. return val;
  69271. };
  69272. /**
  69273. * Check if there's a given key in the dictionary
  69274. * @param key the key to check for
  69275. * @return true if the key is present, false otherwise
  69276. */
  69277. StringDictionary.prototype.contains = function (key) {
  69278. return this._data[key] !== undefined;
  69279. };
  69280. /**
  69281. * Add a new key and its corresponding value
  69282. * @param key the key to add
  69283. * @param value the value corresponding to the key
  69284. * @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
  69285. */
  69286. StringDictionary.prototype.add = function (key, value) {
  69287. if (this._data[key] !== undefined) {
  69288. return false;
  69289. }
  69290. this._data[key] = value;
  69291. ++this._count;
  69292. return true;
  69293. };
  69294. StringDictionary.prototype.set = function (key, value) {
  69295. if (this._data[key] === undefined) {
  69296. return false;
  69297. }
  69298. this._data[key] = value;
  69299. return true;
  69300. };
  69301. /**
  69302. * Get the element of the given key and remove it from the dictionary
  69303. * @param key
  69304. */
  69305. StringDictionary.prototype.getAndRemove = function (key) {
  69306. var val = this.get(key);
  69307. if (val !== undefined) {
  69308. delete this._data[key];
  69309. --this._count;
  69310. return val;
  69311. }
  69312. return null;
  69313. };
  69314. /**
  69315. * Remove a key/value from the dictionary.
  69316. * @param key the key to remove
  69317. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69318. */
  69319. StringDictionary.prototype.remove = function (key) {
  69320. if (this.contains(key)) {
  69321. delete this._data[key];
  69322. --this._count;
  69323. return true;
  69324. }
  69325. return false;
  69326. };
  69327. /**
  69328. * Clear the whole content of the dictionary
  69329. */
  69330. StringDictionary.prototype.clear = function () {
  69331. this._data = {};
  69332. this._count = 0;
  69333. };
  69334. Object.defineProperty(StringDictionary.prototype, "count", {
  69335. get: function () {
  69336. return this._count;
  69337. },
  69338. enumerable: true,
  69339. configurable: true
  69340. });
  69341. /**
  69342. * Execute a callback on each key/val of the dictionary.
  69343. * Note that you can remove any element in this dictionary in the callback implementation
  69344. * @param callback the callback to execute on a given key/value pair
  69345. */
  69346. StringDictionary.prototype.forEach = function (callback) {
  69347. for (var cur in this._data) {
  69348. var val = this._data[cur];
  69349. callback(cur, val);
  69350. }
  69351. };
  69352. /**
  69353. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69354. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69355. * Note that you can remove any element in this dictionary in the callback implementation
  69356. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69357. */
  69358. StringDictionary.prototype.first = function (callback) {
  69359. for (var cur in this._data) {
  69360. var val = this._data[cur];
  69361. var res = callback(cur, val);
  69362. if (res) {
  69363. return res;
  69364. }
  69365. }
  69366. return null;
  69367. };
  69368. return StringDictionary;
  69369. }());
  69370. BABYLON.StringDictionary = StringDictionary;
  69371. })(BABYLON || (BABYLON = {}));
  69372. //# sourceMappingURL=babylon.stringDictionary.js.map
  69373. var BABYLON;
  69374. (function (BABYLON) {
  69375. var Tags = /** @class */ (function () {
  69376. function Tags() {
  69377. }
  69378. Tags.EnableFor = function (obj) {
  69379. obj._tags = obj._tags || {};
  69380. obj.hasTags = function () {
  69381. return Tags.HasTags(obj);
  69382. };
  69383. obj.addTags = function (tagsString) {
  69384. return Tags.AddTagsTo(obj, tagsString);
  69385. };
  69386. obj.removeTags = function (tagsString) {
  69387. return Tags.RemoveTagsFrom(obj, tagsString);
  69388. };
  69389. obj.matchesTagsQuery = function (tagsQuery) {
  69390. return Tags.MatchesQuery(obj, tagsQuery);
  69391. };
  69392. };
  69393. Tags.DisableFor = function (obj) {
  69394. delete obj._tags;
  69395. delete obj.hasTags;
  69396. delete obj.addTags;
  69397. delete obj.removeTags;
  69398. delete obj.matchesTagsQuery;
  69399. };
  69400. Tags.HasTags = function (obj) {
  69401. if (!obj._tags) {
  69402. return false;
  69403. }
  69404. return !BABYLON.Tools.IsEmpty(obj._tags);
  69405. };
  69406. Tags.GetTags = function (obj, asString) {
  69407. if (asString === void 0) { asString = true; }
  69408. if (!obj._tags) {
  69409. return null;
  69410. }
  69411. if (asString) {
  69412. var tagsArray = [];
  69413. for (var tag in obj._tags) {
  69414. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69415. tagsArray.push(tag);
  69416. }
  69417. }
  69418. return tagsArray.join(" ");
  69419. }
  69420. else {
  69421. return obj._tags;
  69422. }
  69423. };
  69424. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69425. // a tag cannot start with '||', '&&', and '!'
  69426. // it cannot contain whitespaces
  69427. Tags.AddTagsTo = function (obj, tagsString) {
  69428. if (!tagsString) {
  69429. return;
  69430. }
  69431. if (typeof tagsString !== "string") {
  69432. return;
  69433. }
  69434. var tags = tagsString.split(" ");
  69435. tags.forEach(function (tag, index, array) {
  69436. Tags._AddTagTo(obj, tag);
  69437. });
  69438. };
  69439. Tags._AddTagTo = function (obj, tag) {
  69440. tag = tag.trim();
  69441. if (tag === "" || tag === "true" || tag === "false") {
  69442. return;
  69443. }
  69444. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69445. return;
  69446. }
  69447. Tags.EnableFor(obj);
  69448. obj._tags[tag] = true;
  69449. };
  69450. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69451. if (!Tags.HasTags(obj)) {
  69452. return;
  69453. }
  69454. var tags = tagsString.split(" ");
  69455. for (var t in tags) {
  69456. Tags._RemoveTagFrom(obj, tags[t]);
  69457. }
  69458. };
  69459. Tags._RemoveTagFrom = function (obj, tag) {
  69460. delete obj._tags[tag];
  69461. };
  69462. Tags.MatchesQuery = function (obj, tagsQuery) {
  69463. if (tagsQuery === undefined) {
  69464. return true;
  69465. }
  69466. if (tagsQuery === "") {
  69467. return Tags.HasTags(obj);
  69468. }
  69469. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69470. };
  69471. return Tags;
  69472. }());
  69473. BABYLON.Tags = Tags;
  69474. })(BABYLON || (BABYLON = {}));
  69475. //# sourceMappingURL=babylon.tags.js.map
  69476. var BABYLON;
  69477. (function (BABYLON) {
  69478. /**
  69479. * Class used to evalaute queries containing `and` and `or` operators
  69480. */
  69481. var AndOrNotEvaluator = /** @class */ (function () {
  69482. function AndOrNotEvaluator() {
  69483. }
  69484. /**
  69485. * Evaluate a query
  69486. * @param query defines the query to evaluate
  69487. * @param evaluateCallback defines the callback used to filter result
  69488. * @returns true if the query matches
  69489. */
  69490. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69491. if (!query.match(/\([^\(\)]*\)/g)) {
  69492. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69493. }
  69494. else {
  69495. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69496. // remove parenthesis
  69497. r = r.slice(1, r.length - 1);
  69498. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69499. });
  69500. }
  69501. if (query === "true") {
  69502. return true;
  69503. }
  69504. if (query === "false") {
  69505. return false;
  69506. }
  69507. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69508. };
  69509. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69510. evaluateCallback = evaluateCallback || (function (r) {
  69511. return r === "true" ? true : false;
  69512. });
  69513. var result;
  69514. var or = parenthesisContent.split("||");
  69515. for (var i in or) {
  69516. if (or.hasOwnProperty(i)) {
  69517. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69518. var and = ori.split("&&");
  69519. if (and.length > 1) {
  69520. for (var j = 0; j < and.length; ++j) {
  69521. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69522. if (andj !== "true" && andj !== "false") {
  69523. if (andj[0] === "!") {
  69524. result = !evaluateCallback(andj.substring(1));
  69525. }
  69526. else {
  69527. result = evaluateCallback(andj);
  69528. }
  69529. }
  69530. else {
  69531. result = andj === "true" ? true : false;
  69532. }
  69533. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69534. ori = "false";
  69535. break;
  69536. }
  69537. }
  69538. }
  69539. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69540. result = true;
  69541. break;
  69542. }
  69543. // result equals false (or undefined)
  69544. if (ori !== "true" && ori !== "false") {
  69545. if (ori[0] === "!") {
  69546. result = !evaluateCallback(ori.substring(1));
  69547. }
  69548. else {
  69549. result = evaluateCallback(ori);
  69550. }
  69551. }
  69552. else {
  69553. result = ori === "true" ? true : false;
  69554. }
  69555. }
  69556. }
  69557. // the whole parenthesis scope is replaced by 'true' or 'false'
  69558. return result ? "true" : "false";
  69559. };
  69560. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69561. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69562. // remove whitespaces
  69563. r = r.replace(/[\s]/g, function () { return ""; });
  69564. return r.length % 2 ? "!" : "";
  69565. });
  69566. booleanString = booleanString.trim();
  69567. if (booleanString === "!true") {
  69568. booleanString = "false";
  69569. }
  69570. else if (booleanString === "!false") {
  69571. booleanString = "true";
  69572. }
  69573. return booleanString;
  69574. };
  69575. return AndOrNotEvaluator;
  69576. }());
  69577. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69578. })(BABYLON || (BABYLON = {}));
  69579. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69580. var BABYLON;
  69581. (function (BABYLON) {
  69582. /**
  69583. * Class used to enable access to IndexedDB
  69584. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69585. */
  69586. var Database = /** @class */ (function () {
  69587. /**
  69588. * Creates a new Database
  69589. * @param urlToScene defines the url to load the scene
  69590. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69591. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69592. */
  69593. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69594. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69595. var _this = this;
  69596. // Handling various flavors of prefixed version of IndexedDB
  69597. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69598. this.callbackManifestChecked = callbackManifestChecked;
  69599. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69600. this.db = null;
  69601. this._enableSceneOffline = false;
  69602. this._enableTexturesOffline = false;
  69603. this.manifestVersionFound = 0;
  69604. this.mustUpdateRessources = false;
  69605. this.hasReachedQuota = false;
  69606. if (!Database.IDBStorageEnabled) {
  69607. this.callbackManifestChecked(true);
  69608. }
  69609. else {
  69610. if (disableManifestCheck) {
  69611. this._enableSceneOffline = true;
  69612. this._enableTexturesOffline = true;
  69613. this.manifestVersionFound = 1;
  69614. BABYLON.Tools.SetImmediate(function () {
  69615. _this.callbackManifestChecked(true);
  69616. });
  69617. }
  69618. else {
  69619. this._checkManifestFile();
  69620. }
  69621. }
  69622. }
  69623. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69624. /**
  69625. * Gets a boolean indicating if scene must be saved in the database
  69626. */
  69627. get: function () {
  69628. return this._enableSceneOffline;
  69629. },
  69630. enumerable: true,
  69631. configurable: true
  69632. });
  69633. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69634. /**
  69635. * Gets a boolean indicating if textures must be saved in the database
  69636. */
  69637. get: function () {
  69638. return this._enableTexturesOffline;
  69639. },
  69640. enumerable: true,
  69641. configurable: true
  69642. });
  69643. Database.prototype._checkManifestFile = function () {
  69644. var _this = this;
  69645. var noManifestFile = function () {
  69646. _this._enableSceneOffline = false;
  69647. _this._enableTexturesOffline = false;
  69648. _this.callbackManifestChecked(false);
  69649. };
  69650. var timeStampUsed = false;
  69651. var manifestURL = this.currentSceneUrl + ".manifest";
  69652. var xhr = new XMLHttpRequest();
  69653. if (navigator.onLine) {
  69654. // Adding a timestamp to by-pass browsers' cache
  69655. timeStampUsed = true;
  69656. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69657. }
  69658. xhr.open("GET", manifestURL, true);
  69659. xhr.addEventListener("load", function () {
  69660. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69661. try {
  69662. var manifestFile = JSON.parse(xhr.response);
  69663. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69664. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69665. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69666. _this.manifestVersionFound = manifestFile.version;
  69667. }
  69668. if (_this.callbackManifestChecked) {
  69669. _this.callbackManifestChecked(true);
  69670. }
  69671. }
  69672. catch (ex) {
  69673. noManifestFile();
  69674. }
  69675. }
  69676. else {
  69677. noManifestFile();
  69678. }
  69679. }, false);
  69680. xhr.addEventListener("error", function (event) {
  69681. if (timeStampUsed) {
  69682. timeStampUsed = false;
  69683. // Let's retry without the timeStamp
  69684. // It could fail when coupled with HTML5 Offline API
  69685. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69686. xhr.open("GET", retryManifestURL, true);
  69687. xhr.send();
  69688. }
  69689. else {
  69690. noManifestFile();
  69691. }
  69692. }, false);
  69693. try {
  69694. xhr.send();
  69695. }
  69696. catch (ex) {
  69697. BABYLON.Tools.Error("Error on XHR send request.");
  69698. this.callbackManifestChecked(false);
  69699. }
  69700. };
  69701. /**
  69702. * Open the database and make it available
  69703. * @param successCallback defines the callback to call on success
  69704. * @param errorCallback defines the callback to call on error
  69705. */
  69706. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69707. var _this = this;
  69708. var handleError = function () {
  69709. _this.isSupported = false;
  69710. if (errorCallback)
  69711. errorCallback();
  69712. };
  69713. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69714. // Your browser doesn't support IndexedDB
  69715. this.isSupported = false;
  69716. if (errorCallback)
  69717. errorCallback();
  69718. }
  69719. else {
  69720. // If the DB hasn't been opened or created yet
  69721. if (!this.db) {
  69722. this.hasReachedQuota = false;
  69723. this.isSupported = true;
  69724. var request = this.idbFactory.open("babylonjs", 1);
  69725. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69726. request.onerror = function (event) {
  69727. handleError();
  69728. };
  69729. // executes when a version change transaction cannot complete due to other active transactions
  69730. request.onblocked = function (event) {
  69731. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69732. handleError();
  69733. };
  69734. // DB has been opened successfully
  69735. request.onsuccess = function (event) {
  69736. _this.db = request.result;
  69737. successCallback();
  69738. };
  69739. // Initialization of the DB. Creating Scenes & Textures stores
  69740. request.onupgradeneeded = function (event) {
  69741. _this.db = (event.target).result;
  69742. if (_this.db) {
  69743. try {
  69744. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69745. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69746. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69747. }
  69748. catch (ex) {
  69749. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69750. handleError();
  69751. }
  69752. }
  69753. };
  69754. }
  69755. // DB has already been created and opened
  69756. else {
  69757. if (successCallback)
  69758. successCallback();
  69759. }
  69760. }
  69761. };
  69762. /**
  69763. * Loads an image from the database
  69764. * @param url defines the url to load from
  69765. * @param image defines the target DOM image
  69766. */
  69767. Database.prototype.loadImageFromDB = function (url, image) {
  69768. var _this = this;
  69769. var completeURL = Database._ReturnFullUrlLocation(url);
  69770. var saveAndLoadImage = function () {
  69771. if (!_this.hasReachedQuota && _this.db !== null) {
  69772. // the texture is not yet in the DB, let's try to save it
  69773. _this._saveImageIntoDBAsync(completeURL, image);
  69774. }
  69775. // If the texture is not in the DB and we've reached the DB quota limit
  69776. // let's load it directly from the web
  69777. else {
  69778. image.src = url;
  69779. }
  69780. };
  69781. if (!this.mustUpdateRessources) {
  69782. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69783. }
  69784. // First time we're download the images or update requested in the manifest file by a version change
  69785. else {
  69786. saveAndLoadImage();
  69787. }
  69788. };
  69789. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69790. if (this.isSupported && this.db !== null) {
  69791. var texture;
  69792. var transaction = this.db.transaction(["textures"]);
  69793. transaction.onabort = function (event) {
  69794. image.src = url;
  69795. };
  69796. transaction.oncomplete = function (event) {
  69797. var blobTextureURL;
  69798. if (texture) {
  69799. var URL = window.URL || window.webkitURL;
  69800. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69801. image.onerror = function () {
  69802. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69803. image.src = url;
  69804. };
  69805. image.src = blobTextureURL;
  69806. }
  69807. else {
  69808. notInDBCallback();
  69809. }
  69810. };
  69811. var getRequest = transaction.objectStore("textures").get(url);
  69812. getRequest.onsuccess = function (event) {
  69813. texture = (event.target).result;
  69814. };
  69815. getRequest.onerror = function (event) {
  69816. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69817. image.src = url;
  69818. };
  69819. }
  69820. else {
  69821. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69822. image.src = url;
  69823. }
  69824. };
  69825. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69826. var _this = this;
  69827. if (this.isSupported) {
  69828. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69829. var generateBlobUrl = function () {
  69830. var blobTextureURL;
  69831. if (blob) {
  69832. var URL = window.URL || window.webkitURL;
  69833. try {
  69834. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69835. }
  69836. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69837. catch (ex) {
  69838. blobTextureURL = URL.createObjectURL(blob);
  69839. }
  69840. }
  69841. if (blobTextureURL) {
  69842. image.src = blobTextureURL;
  69843. }
  69844. };
  69845. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69846. var xhr = new XMLHttpRequest(), blob;
  69847. xhr.open("GET", url, true);
  69848. xhr.responseType = "blob";
  69849. xhr.addEventListener("load", function () {
  69850. if (xhr.status === 200 && _this.db) {
  69851. // Blob as response (XHR2)
  69852. blob = xhr.response;
  69853. var transaction = _this.db.transaction(["textures"], "readwrite");
  69854. // the transaction could abort because of a QuotaExceededError error
  69855. transaction.onabort = function (event) {
  69856. try {
  69857. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69858. var srcElement = (event.srcElement || event.target);
  69859. var error = srcElement.error;
  69860. if (error && error.name === "QuotaExceededError") {
  69861. _this.hasReachedQuota = true;
  69862. }
  69863. }
  69864. catch (ex) { }
  69865. generateBlobUrl();
  69866. };
  69867. transaction.oncomplete = function (event) {
  69868. generateBlobUrl();
  69869. };
  69870. var newTexture = { textureUrl: url, data: blob };
  69871. try {
  69872. // Put the blob into the dabase
  69873. var addRequest = transaction.objectStore("textures").put(newTexture);
  69874. addRequest.onsuccess = function (event) {
  69875. };
  69876. addRequest.onerror = function (event) {
  69877. generateBlobUrl();
  69878. };
  69879. }
  69880. catch (ex) {
  69881. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69882. if (ex.code === 25) {
  69883. Database.IsUASupportingBlobStorage = false;
  69884. }
  69885. image.src = url;
  69886. }
  69887. }
  69888. else {
  69889. image.src = url;
  69890. }
  69891. }, false);
  69892. xhr.addEventListener("error", function (event) {
  69893. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69894. image.src = url;
  69895. }, false);
  69896. xhr.send();
  69897. }
  69898. else {
  69899. image.src = url;
  69900. }
  69901. }
  69902. else {
  69903. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69904. image.src = url;
  69905. }
  69906. };
  69907. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69908. var _this = this;
  69909. var updateVersion = function () {
  69910. // the version is not yet in the DB or we need to update it
  69911. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69912. };
  69913. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69914. };
  69915. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69916. var _this = this;
  69917. if (this.isSupported && this.db) {
  69918. var version;
  69919. try {
  69920. var transaction = this.db.transaction(["versions"]);
  69921. transaction.oncomplete = function (event) {
  69922. if (version) {
  69923. // If the version in the JSON file is different from the version in DB
  69924. if (_this.manifestVersionFound !== version.data) {
  69925. _this.mustUpdateRessources = true;
  69926. updateInDBCallback();
  69927. }
  69928. else {
  69929. callback(version.data);
  69930. }
  69931. }
  69932. // version was not found in DB
  69933. else {
  69934. _this.mustUpdateRessources = true;
  69935. updateInDBCallback();
  69936. }
  69937. };
  69938. transaction.onabort = function (event) {
  69939. callback(-1);
  69940. };
  69941. var getRequest = transaction.objectStore("versions").get(url);
  69942. getRequest.onsuccess = function (event) {
  69943. version = (event.target).result;
  69944. };
  69945. getRequest.onerror = function (event) {
  69946. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69947. callback(-1);
  69948. };
  69949. }
  69950. catch (ex) {
  69951. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69952. callback(-1);
  69953. }
  69954. }
  69955. else {
  69956. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69957. callback(-1);
  69958. }
  69959. };
  69960. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69961. var _this = this;
  69962. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69963. try {
  69964. // Open a transaction to the database
  69965. var transaction = this.db.transaction(["versions"], "readwrite");
  69966. // the transaction could abort because of a QuotaExceededError error
  69967. transaction.onabort = function (event) {
  69968. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69969. var error = event.srcElement['error'];
  69970. if (error && error.name === "QuotaExceededError") {
  69971. _this.hasReachedQuota = true;
  69972. }
  69973. }
  69974. catch (ex) { }
  69975. callback(-1);
  69976. };
  69977. transaction.oncomplete = function (event) {
  69978. callback(_this.manifestVersionFound);
  69979. };
  69980. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69981. // Put the scene into the database
  69982. var addRequest = transaction.objectStore("versions").put(newVersion);
  69983. addRequest.onsuccess = function (event) {
  69984. };
  69985. addRequest.onerror = function (event) {
  69986. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69987. };
  69988. }
  69989. catch (ex) {
  69990. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69991. callback(-1);
  69992. }
  69993. }
  69994. else {
  69995. callback(-1);
  69996. }
  69997. };
  69998. /**
  69999. * Loads a file from database
  70000. * @param url defines the URL to load from
  70001. * @param sceneLoaded defines a callback to call on success
  70002. * @param progressCallBack defines a callback to call when progress changed
  70003. * @param errorCallback defines a callback to call on error
  70004. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  70005. */
  70006. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  70007. var _this = this;
  70008. var completeUrl = Database._ReturnFullUrlLocation(url);
  70009. var saveAndLoadFile = function () {
  70010. // the scene is not yet in the DB, let's try to save it
  70011. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  70012. };
  70013. this._checkVersionFromDB(completeUrl, function (version) {
  70014. if (version !== -1) {
  70015. if (!_this.mustUpdateRessources) {
  70016. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  70017. }
  70018. else {
  70019. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  70020. }
  70021. }
  70022. else {
  70023. if (errorCallback) {
  70024. errorCallback();
  70025. }
  70026. }
  70027. });
  70028. };
  70029. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  70030. if (this.isSupported && this.db) {
  70031. var targetStore;
  70032. if (url.indexOf(".babylon") !== -1) {
  70033. targetStore = "scenes";
  70034. }
  70035. else {
  70036. targetStore = "textures";
  70037. }
  70038. var file;
  70039. var transaction = this.db.transaction([targetStore]);
  70040. transaction.oncomplete = function (event) {
  70041. if (file) {
  70042. callback(file.data);
  70043. }
  70044. // file was not found in DB
  70045. else {
  70046. notInDBCallback();
  70047. }
  70048. };
  70049. transaction.onabort = function (event) {
  70050. notInDBCallback();
  70051. };
  70052. var getRequest = transaction.objectStore(targetStore).get(url);
  70053. getRequest.onsuccess = function (event) {
  70054. file = (event.target).result;
  70055. };
  70056. getRequest.onerror = function (event) {
  70057. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  70058. notInDBCallback();
  70059. };
  70060. }
  70061. else {
  70062. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70063. callback();
  70064. }
  70065. };
  70066. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  70067. var _this = this;
  70068. if (this.isSupported) {
  70069. var targetStore;
  70070. if (url.indexOf(".babylon") !== -1) {
  70071. targetStore = "scenes";
  70072. }
  70073. else {
  70074. targetStore = "textures";
  70075. }
  70076. // Create XHR
  70077. var xhr = new XMLHttpRequest();
  70078. var fileData;
  70079. xhr.open("GET", url, true);
  70080. if (useArrayBuffer) {
  70081. xhr.responseType = "arraybuffer";
  70082. }
  70083. if (progressCallback) {
  70084. xhr.onprogress = progressCallback;
  70085. }
  70086. xhr.addEventListener("load", function () {
  70087. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  70088. // Blob as response (XHR2)
  70089. //fileData = xhr.responseText;
  70090. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  70091. if (!_this.hasReachedQuota && _this.db) {
  70092. // Open a transaction to the database
  70093. var transaction = _this.db.transaction([targetStore], "readwrite");
  70094. // the transaction could abort because of a QuotaExceededError error
  70095. transaction.onabort = function (event) {
  70096. try {
  70097. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  70098. var error = event.srcElement['error'];
  70099. if (error && error.name === "QuotaExceededError") {
  70100. _this.hasReachedQuota = true;
  70101. }
  70102. }
  70103. catch (ex) { }
  70104. callback(fileData);
  70105. };
  70106. transaction.oncomplete = function (event) {
  70107. callback(fileData);
  70108. };
  70109. var newFile;
  70110. if (targetStore === "scenes") {
  70111. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  70112. }
  70113. else {
  70114. newFile = { textureUrl: url, data: fileData };
  70115. }
  70116. try {
  70117. // Put the scene into the database
  70118. var addRequest = transaction.objectStore(targetStore).put(newFile);
  70119. addRequest.onsuccess = function (event) {
  70120. };
  70121. addRequest.onerror = function (event) {
  70122. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  70123. };
  70124. }
  70125. catch (ex) {
  70126. callback(fileData);
  70127. }
  70128. }
  70129. else {
  70130. callback(fileData);
  70131. }
  70132. }
  70133. else {
  70134. callback();
  70135. }
  70136. }, false);
  70137. xhr.addEventListener("error", function (event) {
  70138. BABYLON.Tools.Error("error on XHR request.");
  70139. callback();
  70140. }, false);
  70141. xhr.send();
  70142. }
  70143. else {
  70144. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  70145. callback();
  70146. }
  70147. };
  70148. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  70149. Database.IsUASupportingBlobStorage = true;
  70150. /** Gets a boolean indicating if Database storate is enabled */
  70151. Database.IDBStorageEnabled = true;
  70152. Database._ParseURL = function (url) {
  70153. var a = document.createElement('a');
  70154. a.href = url;
  70155. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  70156. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  70157. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  70158. return absLocation;
  70159. };
  70160. Database._ReturnFullUrlLocation = function (url) {
  70161. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  70162. return (Database._ParseURL(window.location.href) + url);
  70163. }
  70164. else {
  70165. return url;
  70166. }
  70167. };
  70168. return Database;
  70169. }());
  70170. BABYLON.Database = Database;
  70171. })(BABYLON || (BABYLON = {}));
  70172. //# sourceMappingURL=babylon.database.js.map
  70173. var BABYLON;
  70174. (function (BABYLON) {
  70175. var FresnelParameters = /** @class */ (function () {
  70176. function FresnelParameters() {
  70177. this._isEnabled = true;
  70178. this.leftColor = BABYLON.Color3.White();
  70179. this.rightColor = BABYLON.Color3.Black();
  70180. this.bias = 0;
  70181. this.power = 1;
  70182. }
  70183. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  70184. get: function () {
  70185. return this._isEnabled;
  70186. },
  70187. set: function (value) {
  70188. if (this._isEnabled === value) {
  70189. return;
  70190. }
  70191. this._isEnabled = value;
  70192. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  70193. },
  70194. enumerable: true,
  70195. configurable: true
  70196. });
  70197. FresnelParameters.prototype.clone = function () {
  70198. var newFresnelParameters = new FresnelParameters();
  70199. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  70200. return newFresnelParameters;
  70201. };
  70202. FresnelParameters.prototype.serialize = function () {
  70203. var serializationObject = {};
  70204. serializationObject.isEnabled = this.isEnabled;
  70205. serializationObject.leftColor = this.leftColor.asArray();
  70206. serializationObject.rightColor = this.rightColor.asArray();
  70207. serializationObject.bias = this.bias;
  70208. serializationObject.power = this.power;
  70209. return serializationObject;
  70210. };
  70211. FresnelParameters.Parse = function (parsedFresnelParameters) {
  70212. var fresnelParameters = new FresnelParameters();
  70213. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  70214. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  70215. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  70216. fresnelParameters.bias = parsedFresnelParameters.bias;
  70217. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  70218. return fresnelParameters;
  70219. };
  70220. return FresnelParameters;
  70221. }());
  70222. BABYLON.FresnelParameters = FresnelParameters;
  70223. })(BABYLON || (BABYLON = {}));
  70224. //# sourceMappingURL=babylon.fresnelParameters.js.map
  70225. var BABYLON;
  70226. (function (BABYLON) {
  70227. var MultiMaterial = /** @class */ (function (_super) {
  70228. __extends(MultiMaterial, _super);
  70229. function MultiMaterial(name, scene) {
  70230. var _this = _super.call(this, name, scene, true) || this;
  70231. scene.multiMaterials.push(_this);
  70232. _this.subMaterials = new Array();
  70233. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70234. return _this;
  70235. }
  70236. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70237. get: function () {
  70238. return this._subMaterials;
  70239. },
  70240. set: function (value) {
  70241. this._subMaterials = value;
  70242. this._hookArray(value);
  70243. },
  70244. enumerable: true,
  70245. configurable: true
  70246. });
  70247. MultiMaterial.prototype._hookArray = function (array) {
  70248. var _this = this;
  70249. var oldPush = array.push;
  70250. array.push = function () {
  70251. var items = [];
  70252. for (var _i = 0; _i < arguments.length; _i++) {
  70253. items[_i] = arguments[_i];
  70254. }
  70255. var result = oldPush.apply(array, items);
  70256. _this._markAllSubMeshesAsTexturesDirty();
  70257. return result;
  70258. };
  70259. var oldSplice = array.splice;
  70260. array.splice = function (index, deleteCount) {
  70261. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70262. _this._markAllSubMeshesAsTexturesDirty();
  70263. return deleted;
  70264. };
  70265. };
  70266. // Properties
  70267. MultiMaterial.prototype.getSubMaterial = function (index) {
  70268. if (index < 0 || index >= this.subMaterials.length) {
  70269. return this.getScene().defaultMaterial;
  70270. }
  70271. return this.subMaterials[index];
  70272. };
  70273. MultiMaterial.prototype.getActiveTextures = function () {
  70274. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70275. if (subMaterial) {
  70276. return subMaterial.getActiveTextures();
  70277. }
  70278. else {
  70279. return [];
  70280. }
  70281. }));
  70282. var _a;
  70283. };
  70284. // Methods
  70285. MultiMaterial.prototype.getClassName = function () {
  70286. return "MultiMaterial";
  70287. };
  70288. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70289. for (var index = 0; index < this.subMaterials.length; index++) {
  70290. var subMaterial = this.subMaterials[index];
  70291. if (subMaterial) {
  70292. if (subMaterial.storeEffectOnSubMeshes) {
  70293. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70294. return false;
  70295. }
  70296. continue;
  70297. }
  70298. if (!subMaterial.isReady(mesh)) {
  70299. return false;
  70300. }
  70301. }
  70302. }
  70303. return true;
  70304. };
  70305. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70306. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70307. for (var index = 0; index < this.subMaterials.length; index++) {
  70308. var subMaterial = null;
  70309. var current = this.subMaterials[index];
  70310. if (cloneChildren && current) {
  70311. subMaterial = current.clone(name + "-" + current.name);
  70312. }
  70313. else {
  70314. subMaterial = this.subMaterials[index];
  70315. }
  70316. newMultiMaterial.subMaterials.push(subMaterial);
  70317. }
  70318. return newMultiMaterial;
  70319. };
  70320. MultiMaterial.prototype.serialize = function () {
  70321. var serializationObject = {};
  70322. serializationObject.name = this.name;
  70323. serializationObject.id = this.id;
  70324. if (BABYLON.Tags) {
  70325. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70326. }
  70327. serializationObject.materials = [];
  70328. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70329. var subMat = this.subMaterials[matIndex];
  70330. if (subMat) {
  70331. serializationObject.materials.push(subMat.id);
  70332. }
  70333. else {
  70334. serializationObject.materials.push(null);
  70335. }
  70336. }
  70337. return serializationObject;
  70338. };
  70339. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70340. var scene = this.getScene();
  70341. if (!scene) {
  70342. return;
  70343. }
  70344. var index = scene.multiMaterials.indexOf(this);
  70345. if (index >= 0) {
  70346. scene.multiMaterials.splice(index, 1);
  70347. }
  70348. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70349. };
  70350. return MultiMaterial;
  70351. }(BABYLON.Material));
  70352. BABYLON.MultiMaterial = MultiMaterial;
  70353. })(BABYLON || (BABYLON = {}));
  70354. //# sourceMappingURL=babylon.multiMaterial.js.map
  70355. var BABYLON;
  70356. (function (BABYLON) {
  70357. var FreeCameraTouchInput = /** @class */ (function () {
  70358. function FreeCameraTouchInput() {
  70359. this._offsetX = null;
  70360. this._offsetY = null;
  70361. this._pointerPressed = new Array();
  70362. this.touchAngularSensibility = 200000.0;
  70363. this.touchMoveSensibility = 250.0;
  70364. }
  70365. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70366. var _this = this;
  70367. var previousPosition = null;
  70368. if (this._pointerInput === undefined) {
  70369. this._onLostFocus = function (evt) {
  70370. _this._offsetX = null;
  70371. _this._offsetY = null;
  70372. };
  70373. this._pointerInput = function (p, s) {
  70374. var evt = p.event;
  70375. if (evt.pointerType === "mouse") {
  70376. return;
  70377. }
  70378. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70379. if (!noPreventDefault) {
  70380. evt.preventDefault();
  70381. }
  70382. _this._pointerPressed.push(evt.pointerId);
  70383. if (_this._pointerPressed.length !== 1) {
  70384. return;
  70385. }
  70386. previousPosition = {
  70387. x: evt.clientX,
  70388. y: evt.clientY
  70389. };
  70390. }
  70391. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70392. if (!noPreventDefault) {
  70393. evt.preventDefault();
  70394. }
  70395. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70396. if (index === -1) {
  70397. return;
  70398. }
  70399. _this._pointerPressed.splice(index, 1);
  70400. if (index != 0) {
  70401. return;
  70402. }
  70403. previousPosition = null;
  70404. _this._offsetX = null;
  70405. _this._offsetY = null;
  70406. }
  70407. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70408. if (!noPreventDefault) {
  70409. evt.preventDefault();
  70410. }
  70411. if (!previousPosition) {
  70412. return;
  70413. }
  70414. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70415. if (index != 0) {
  70416. return;
  70417. }
  70418. _this._offsetX = evt.clientX - previousPosition.x;
  70419. _this._offsetY = -(evt.clientY - previousPosition.y);
  70420. }
  70421. };
  70422. }
  70423. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70424. if (this._onLostFocus) {
  70425. element.addEventListener("blur", this._onLostFocus);
  70426. }
  70427. };
  70428. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70429. if (this._pointerInput && element) {
  70430. if (this._observer) {
  70431. this.camera.getScene().onPointerObservable.remove(this._observer);
  70432. this._observer = null;
  70433. }
  70434. if (this._onLostFocus) {
  70435. element.removeEventListener("blur", this._onLostFocus);
  70436. this._onLostFocus = null;
  70437. }
  70438. this._pointerPressed = [];
  70439. this._offsetX = null;
  70440. this._offsetY = null;
  70441. }
  70442. };
  70443. FreeCameraTouchInput.prototype.checkInputs = function () {
  70444. if (this._offsetX && this._offsetY) {
  70445. var camera = this.camera;
  70446. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70447. if (this._pointerPressed.length > 1) {
  70448. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70449. }
  70450. else {
  70451. var speed = camera._computeLocalCameraSpeed();
  70452. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70453. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70454. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70455. }
  70456. }
  70457. };
  70458. FreeCameraTouchInput.prototype.getClassName = function () {
  70459. return "FreeCameraTouchInput";
  70460. };
  70461. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70462. return "touch";
  70463. };
  70464. __decorate([
  70465. BABYLON.serialize()
  70466. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70467. __decorate([
  70468. BABYLON.serialize()
  70469. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70470. return FreeCameraTouchInput;
  70471. }());
  70472. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70473. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70474. })(BABYLON || (BABYLON = {}));
  70475. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70476. var BABYLON;
  70477. (function (BABYLON) {
  70478. // We're mainly based on the logic defined into the FreeCamera code
  70479. var TouchCamera = /** @class */ (function (_super) {
  70480. __extends(TouchCamera, _super);
  70481. //-- end properties for backward compatibility for inputs
  70482. function TouchCamera(name, position, scene) {
  70483. var _this = _super.call(this, name, position, scene) || this;
  70484. _this.inputs.addTouch();
  70485. _this._setupInputs();
  70486. return _this;
  70487. }
  70488. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70489. //-- Begin properties for backward compatibility for inputs
  70490. get: function () {
  70491. var touch = this.inputs.attached["touch"];
  70492. if (touch)
  70493. return touch.touchAngularSensibility;
  70494. return 0;
  70495. },
  70496. set: function (value) {
  70497. var touch = this.inputs.attached["touch"];
  70498. if (touch)
  70499. touch.touchAngularSensibility = value;
  70500. },
  70501. enumerable: true,
  70502. configurable: true
  70503. });
  70504. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70505. get: function () {
  70506. var touch = this.inputs.attached["touch"];
  70507. if (touch)
  70508. return touch.touchMoveSensibility;
  70509. return 0;
  70510. },
  70511. set: function (value) {
  70512. var touch = this.inputs.attached["touch"];
  70513. if (touch)
  70514. touch.touchMoveSensibility = value;
  70515. },
  70516. enumerable: true,
  70517. configurable: true
  70518. });
  70519. TouchCamera.prototype.getClassName = function () {
  70520. return "TouchCamera";
  70521. };
  70522. TouchCamera.prototype._setupInputs = function () {
  70523. var mouse = this.inputs.attached["mouse"];
  70524. if (mouse) {
  70525. mouse.touchEnabled = false;
  70526. }
  70527. };
  70528. return TouchCamera;
  70529. }(BABYLON.FreeCamera));
  70530. BABYLON.TouchCamera = TouchCamera;
  70531. })(BABYLON || (BABYLON = {}));
  70532. //# sourceMappingURL=babylon.touchCamera.js.map
  70533. var BABYLON;
  70534. (function (BABYLON) {
  70535. var ProceduralTexture = /** @class */ (function (_super) {
  70536. __extends(ProceduralTexture, _super);
  70537. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70538. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70539. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70540. if (isCube === void 0) { isCube = false; }
  70541. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70542. _this.isCube = isCube;
  70543. _this.isEnabled = true;
  70544. _this._currentRefreshId = -1;
  70545. _this._refreshRate = 1;
  70546. _this._vertexBuffers = {};
  70547. _this._uniforms = new Array();
  70548. _this._samplers = new Array();
  70549. _this._textures = {};
  70550. _this._floats = {};
  70551. _this._floatsArrays = {};
  70552. _this._colors3 = {};
  70553. _this._colors4 = {};
  70554. _this._vectors2 = {};
  70555. _this._vectors3 = {};
  70556. _this._matrices = {};
  70557. _this._fallbackTextureUsed = false;
  70558. scene.proceduralTextures.push(_this);
  70559. _this._engine = scene.getEngine();
  70560. _this.name = name;
  70561. _this.isRenderTarget = true;
  70562. _this._size = size;
  70563. _this._generateMipMaps = generateMipMaps;
  70564. _this.setFragment(fragment);
  70565. _this._fallbackTexture = fallbackTexture;
  70566. if (isCube) {
  70567. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70568. _this.setFloat("face", 0);
  70569. }
  70570. else {
  70571. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70572. }
  70573. // VBO
  70574. var vertices = [];
  70575. vertices.push(1, 1);
  70576. vertices.push(-1, 1);
  70577. vertices.push(-1, -1);
  70578. vertices.push(1, -1);
  70579. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70580. _this._createIndexBuffer();
  70581. return _this;
  70582. }
  70583. ProceduralTexture.prototype._createIndexBuffer = function () {
  70584. var engine = this._engine;
  70585. // Indices
  70586. var indices = [];
  70587. indices.push(0);
  70588. indices.push(1);
  70589. indices.push(2);
  70590. indices.push(0);
  70591. indices.push(2);
  70592. indices.push(3);
  70593. this._indexBuffer = engine.createIndexBuffer(indices);
  70594. };
  70595. ProceduralTexture.prototype._rebuild = function () {
  70596. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70597. if (vb) {
  70598. vb._rebuild();
  70599. }
  70600. this._createIndexBuffer();
  70601. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70602. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70603. }
  70604. };
  70605. ProceduralTexture.prototype.reset = function () {
  70606. if (this._effect === undefined) {
  70607. return;
  70608. }
  70609. var engine = this._engine;
  70610. engine._releaseEffect(this._effect);
  70611. };
  70612. ProceduralTexture.prototype.isReady = function () {
  70613. var _this = this;
  70614. var engine = this._engine;
  70615. var shaders;
  70616. if (!this._fragment) {
  70617. return false;
  70618. }
  70619. if (this._fallbackTextureUsed) {
  70620. return true;
  70621. }
  70622. if (this._fragment.fragmentElement !== undefined) {
  70623. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70624. }
  70625. else {
  70626. shaders = { vertex: "procedural", fragment: this._fragment };
  70627. }
  70628. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70629. _this.releaseInternalTexture();
  70630. if (_this._fallbackTexture) {
  70631. _this._texture = _this._fallbackTexture._texture;
  70632. if (_this._texture) {
  70633. _this._texture.incrementReferences();
  70634. }
  70635. }
  70636. _this._fallbackTextureUsed = true;
  70637. });
  70638. return this._effect.isReady();
  70639. };
  70640. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70641. this._currentRefreshId = -1;
  70642. };
  70643. ProceduralTexture.prototype.setFragment = function (fragment) {
  70644. this._fragment = fragment;
  70645. };
  70646. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70647. get: function () {
  70648. return this._refreshRate;
  70649. },
  70650. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70651. set: function (value) {
  70652. this._refreshRate = value;
  70653. this.resetRefreshCounter();
  70654. },
  70655. enumerable: true,
  70656. configurable: true
  70657. });
  70658. ProceduralTexture.prototype._shouldRender = function () {
  70659. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70660. return false;
  70661. }
  70662. if (this._fallbackTextureUsed) {
  70663. return false;
  70664. }
  70665. if (this._currentRefreshId === -1) { // At least render once
  70666. this._currentRefreshId = 1;
  70667. return true;
  70668. }
  70669. if (this.refreshRate === this._currentRefreshId) {
  70670. this._currentRefreshId = 1;
  70671. return true;
  70672. }
  70673. this._currentRefreshId++;
  70674. return false;
  70675. };
  70676. ProceduralTexture.prototype.getRenderSize = function () {
  70677. return this._size;
  70678. };
  70679. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70680. if (this._fallbackTextureUsed) {
  70681. return;
  70682. }
  70683. this.releaseInternalTexture();
  70684. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70685. // Update properties
  70686. this._size = size;
  70687. this._generateMipMaps = generateMipMaps;
  70688. };
  70689. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70690. if (this._uniforms.indexOf(uniformName) === -1) {
  70691. this._uniforms.push(uniformName);
  70692. }
  70693. };
  70694. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70695. if (this._samplers.indexOf(name) === -1) {
  70696. this._samplers.push(name);
  70697. }
  70698. this._textures[name] = texture;
  70699. return this;
  70700. };
  70701. ProceduralTexture.prototype.setFloat = function (name, value) {
  70702. this._checkUniform(name);
  70703. this._floats[name] = value;
  70704. return this;
  70705. };
  70706. ProceduralTexture.prototype.setFloats = function (name, value) {
  70707. this._checkUniform(name);
  70708. this._floatsArrays[name] = value;
  70709. return this;
  70710. };
  70711. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70712. this._checkUniform(name);
  70713. this._colors3[name] = value;
  70714. return this;
  70715. };
  70716. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70717. this._checkUniform(name);
  70718. this._colors4[name] = value;
  70719. return this;
  70720. };
  70721. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70722. this._checkUniform(name);
  70723. this._vectors2[name] = value;
  70724. return this;
  70725. };
  70726. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70727. this._checkUniform(name);
  70728. this._vectors3[name] = value;
  70729. return this;
  70730. };
  70731. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70732. this._checkUniform(name);
  70733. this._matrices[name] = value;
  70734. return this;
  70735. };
  70736. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70737. var scene = this.getScene();
  70738. if (!scene) {
  70739. return;
  70740. }
  70741. var engine = this._engine;
  70742. // Render
  70743. engine.enableEffect(this._effect);
  70744. engine.setState(false);
  70745. // Texture
  70746. for (var name in this._textures) {
  70747. this._effect.setTexture(name, this._textures[name]);
  70748. }
  70749. // Float
  70750. for (name in this._floats) {
  70751. this._effect.setFloat(name, this._floats[name]);
  70752. }
  70753. // Floats
  70754. for (name in this._floatsArrays) {
  70755. this._effect.setArray(name, this._floatsArrays[name]);
  70756. }
  70757. // Color3
  70758. for (name in this._colors3) {
  70759. this._effect.setColor3(name, this._colors3[name]);
  70760. }
  70761. // Color4
  70762. for (name in this._colors4) {
  70763. var color = this._colors4[name];
  70764. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70765. }
  70766. // Vector2
  70767. for (name in this._vectors2) {
  70768. this._effect.setVector2(name, this._vectors2[name]);
  70769. }
  70770. // Vector3
  70771. for (name in this._vectors3) {
  70772. this._effect.setVector3(name, this._vectors3[name]);
  70773. }
  70774. // Matrix
  70775. for (name in this._matrices) {
  70776. this._effect.setMatrix(name, this._matrices[name]);
  70777. }
  70778. if (!this._texture) {
  70779. return;
  70780. }
  70781. if (this.isCube) {
  70782. for (var face = 0; face < 6; face++) {
  70783. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70784. // VBOs
  70785. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70786. this._effect.setFloat("face", face);
  70787. // Clear
  70788. engine.clear(scene.clearColor, true, true, true);
  70789. // Draw order
  70790. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70791. // Mipmaps
  70792. if (face === 5) {
  70793. engine.generateMipMapsForCubemap(this._texture);
  70794. }
  70795. }
  70796. }
  70797. else {
  70798. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70799. // VBOs
  70800. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70801. // Clear
  70802. engine.clear(scene.clearColor, true, true, true);
  70803. // Draw order
  70804. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70805. }
  70806. // Unbind
  70807. engine.unBindFramebuffer(this._texture, this.isCube);
  70808. if (this.onGenerated) {
  70809. this.onGenerated();
  70810. }
  70811. };
  70812. ProceduralTexture.prototype.clone = function () {
  70813. var textureSize = this.getSize();
  70814. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70815. // Base texture
  70816. newTexture.hasAlpha = this.hasAlpha;
  70817. newTexture.level = this.level;
  70818. // RenderTarget Texture
  70819. newTexture.coordinatesMode = this.coordinatesMode;
  70820. return newTexture;
  70821. };
  70822. ProceduralTexture.prototype.dispose = function () {
  70823. var scene = this.getScene();
  70824. if (!scene) {
  70825. return;
  70826. }
  70827. var index = scene.proceduralTextures.indexOf(this);
  70828. if (index >= 0) {
  70829. scene.proceduralTextures.splice(index, 1);
  70830. }
  70831. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70832. if (vertexBuffer) {
  70833. vertexBuffer.dispose();
  70834. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70835. }
  70836. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70837. this._indexBuffer = null;
  70838. }
  70839. _super.prototype.dispose.call(this);
  70840. };
  70841. __decorate([
  70842. BABYLON.serialize()
  70843. ], ProceduralTexture.prototype, "_size", void 0);
  70844. __decorate([
  70845. BABYLON.serialize()
  70846. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70847. __decorate([
  70848. BABYLON.serialize()
  70849. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70850. __decorate([
  70851. BABYLON.serialize()
  70852. ], ProceduralTexture.prototype, "refreshRate", null);
  70853. return ProceduralTexture;
  70854. }(BABYLON.Texture));
  70855. BABYLON.ProceduralTexture = ProceduralTexture;
  70856. })(BABYLON || (BABYLON = {}));
  70857. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70858. var BABYLON;
  70859. (function (BABYLON) {
  70860. var CustomProceduralTexture = /** @class */ (function (_super) {
  70861. __extends(CustomProceduralTexture, _super);
  70862. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70863. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70864. _this._animate = true;
  70865. _this._time = 0;
  70866. _this._texturePath = texturePath;
  70867. //Try to load json
  70868. _this.loadJson(texturePath);
  70869. _this.refreshRate = 1;
  70870. return _this;
  70871. }
  70872. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70873. var _this = this;
  70874. var noConfigFile = function () {
  70875. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70876. try {
  70877. _this.setFragment(_this._texturePath);
  70878. }
  70879. catch (ex) {
  70880. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70881. }
  70882. };
  70883. var configFileUrl = jsonUrl + "/config.json";
  70884. var xhr = new XMLHttpRequest();
  70885. xhr.open("GET", configFileUrl, true);
  70886. xhr.addEventListener("load", function () {
  70887. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70888. try {
  70889. _this._config = JSON.parse(xhr.response);
  70890. _this.updateShaderUniforms();
  70891. _this.updateTextures();
  70892. _this.setFragment(_this._texturePath + "/custom");
  70893. _this._animate = _this._config.animate;
  70894. _this.refreshRate = _this._config.refreshrate;
  70895. }
  70896. catch (ex) {
  70897. noConfigFile();
  70898. }
  70899. }
  70900. else {
  70901. noConfigFile();
  70902. }
  70903. }, false);
  70904. xhr.addEventListener("error", function () {
  70905. noConfigFile();
  70906. }, false);
  70907. try {
  70908. xhr.send();
  70909. }
  70910. catch (ex) {
  70911. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70912. }
  70913. };
  70914. CustomProceduralTexture.prototype.isReady = function () {
  70915. if (!_super.prototype.isReady.call(this)) {
  70916. return false;
  70917. }
  70918. for (var name in this._textures) {
  70919. var texture = this._textures[name];
  70920. if (!texture.isReady()) {
  70921. return false;
  70922. }
  70923. }
  70924. return true;
  70925. };
  70926. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70927. var scene = this.getScene();
  70928. if (this._animate && scene) {
  70929. this._time += scene.getAnimationRatio() * 0.03;
  70930. this.updateShaderUniforms();
  70931. }
  70932. _super.prototype.render.call(this, useCameraPostProcess);
  70933. };
  70934. CustomProceduralTexture.prototype.updateTextures = function () {
  70935. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70936. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70937. }
  70938. };
  70939. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70940. if (this._config) {
  70941. for (var j = 0; j < this._config.uniforms.length; j++) {
  70942. var uniform = this._config.uniforms[j];
  70943. switch (uniform.type) {
  70944. case "float":
  70945. this.setFloat(uniform.name, uniform.value);
  70946. break;
  70947. case "color3":
  70948. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70949. break;
  70950. case "color4":
  70951. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70952. break;
  70953. case "vector2":
  70954. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70955. break;
  70956. case "vector3":
  70957. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70958. break;
  70959. }
  70960. }
  70961. }
  70962. this.setFloat("time", this._time);
  70963. };
  70964. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70965. get: function () {
  70966. return this._animate;
  70967. },
  70968. set: function (value) {
  70969. this._animate = value;
  70970. },
  70971. enumerable: true,
  70972. configurable: true
  70973. });
  70974. return CustomProceduralTexture;
  70975. }(BABYLON.ProceduralTexture));
  70976. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70977. })(BABYLON || (BABYLON = {}));
  70978. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70979. var BABYLON;
  70980. (function (BABYLON) {
  70981. var FreeCameraGamepadInput = /** @class */ (function () {
  70982. function FreeCameraGamepadInput() {
  70983. this.gamepadAngularSensibility = 200;
  70984. this.gamepadMoveSensibility = 40;
  70985. // private members
  70986. this._cameraTransform = BABYLON.Matrix.Identity();
  70987. this._deltaTransform = BABYLON.Vector3.Zero();
  70988. this._vector3 = BABYLON.Vector3.Zero();
  70989. this._vector2 = BABYLON.Vector2.Zero();
  70990. }
  70991. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70992. var _this = this;
  70993. var manager = this.camera.getScene().gamepadManager;
  70994. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70995. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70996. // prioritize XBOX gamepads.
  70997. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70998. _this.gamepad = gamepad;
  70999. }
  71000. }
  71001. });
  71002. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71003. if (_this.gamepad === gamepad) {
  71004. _this.gamepad = null;
  71005. }
  71006. });
  71007. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71008. };
  71009. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  71010. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71011. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71012. this.gamepad = null;
  71013. };
  71014. FreeCameraGamepadInput.prototype.checkInputs = function () {
  71015. if (this.gamepad && this.gamepad.leftStick) {
  71016. var camera = this.camera;
  71017. var LSValues = this.gamepad.leftStick;
  71018. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  71019. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71020. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  71021. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  71022. var RSValues = this.gamepad.rightStick;
  71023. if (RSValues) {
  71024. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  71025. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  71026. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  71027. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  71028. }
  71029. else {
  71030. RSValues = { x: 0, y: 0 };
  71031. }
  71032. if (!camera.rotationQuaternion) {
  71033. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  71034. }
  71035. else {
  71036. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  71037. }
  71038. var speed = camera._computeLocalCameraSpeed() * 50.0;
  71039. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  71040. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  71041. camera.cameraDirection.addInPlace(this._deltaTransform);
  71042. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  71043. camera.cameraRotation.addInPlace(this._vector2);
  71044. }
  71045. };
  71046. FreeCameraGamepadInput.prototype.getClassName = function () {
  71047. return "FreeCameraGamepadInput";
  71048. };
  71049. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  71050. return "gamepad";
  71051. };
  71052. __decorate([
  71053. BABYLON.serialize()
  71054. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  71055. __decorate([
  71056. BABYLON.serialize()
  71057. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71058. return FreeCameraGamepadInput;
  71059. }());
  71060. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  71061. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  71062. })(BABYLON || (BABYLON = {}));
  71063. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  71064. var BABYLON;
  71065. (function (BABYLON) {
  71066. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  71067. function ArcRotateCameraGamepadInput() {
  71068. this.gamepadRotationSensibility = 80;
  71069. this.gamepadMoveSensibility = 40;
  71070. }
  71071. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  71072. var _this = this;
  71073. var manager = this.camera.getScene().gamepadManager;
  71074. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  71075. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  71076. // prioritize XBOX gamepads.
  71077. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  71078. _this.gamepad = gamepad;
  71079. }
  71080. }
  71081. });
  71082. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  71083. if (_this.gamepad === gamepad) {
  71084. _this.gamepad = null;
  71085. }
  71086. });
  71087. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  71088. };
  71089. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  71090. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  71091. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  71092. this.gamepad = null;
  71093. };
  71094. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  71095. if (this.gamepad) {
  71096. var camera = this.camera;
  71097. var RSValues = this.gamepad.rightStick;
  71098. if (RSValues) {
  71099. if (RSValues.x != 0) {
  71100. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  71101. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  71102. camera.inertialAlphaOffset += normalizedRX;
  71103. }
  71104. }
  71105. if (RSValues.y != 0) {
  71106. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  71107. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  71108. camera.inertialBetaOffset += normalizedRY;
  71109. }
  71110. }
  71111. }
  71112. var LSValues = this.gamepad.leftStick;
  71113. if (LSValues && LSValues.y != 0) {
  71114. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  71115. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  71116. this.camera.inertialRadiusOffset -= normalizedLY;
  71117. }
  71118. }
  71119. }
  71120. };
  71121. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  71122. return "ArcRotateCameraGamepadInput";
  71123. };
  71124. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  71125. return "gamepad";
  71126. };
  71127. __decorate([
  71128. BABYLON.serialize()
  71129. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  71130. __decorate([
  71131. BABYLON.serialize()
  71132. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  71133. return ArcRotateCameraGamepadInput;
  71134. }());
  71135. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  71136. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  71137. })(BABYLON || (BABYLON = {}));
  71138. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  71139. var BABYLON;
  71140. (function (BABYLON) {
  71141. var GamepadManager = /** @class */ (function () {
  71142. function GamepadManager(_scene) {
  71143. var _this = this;
  71144. this._scene = _scene;
  71145. this._babylonGamepads = [];
  71146. this._oneGamepadConnected = false;
  71147. this._isMonitoring = false;
  71148. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  71149. if (!BABYLON.Tools.IsWindowObjectExist()) {
  71150. this._gamepadEventSupported = false;
  71151. }
  71152. else {
  71153. this._gamepadEventSupported = 'GamepadEvent' in window;
  71154. this._gamepadSupport = (navigator.getGamepads ||
  71155. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  71156. }
  71157. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  71158. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  71159. for (var i in _this._babylonGamepads) {
  71160. var gamepad = _this._babylonGamepads[i];
  71161. if (gamepad && gamepad._isConnected) {
  71162. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  71163. }
  71164. }
  71165. });
  71166. this._onGamepadConnectedEvent = function (evt) {
  71167. var gamepad = evt.gamepad;
  71168. if (gamepad.index in _this._babylonGamepads) {
  71169. if (_this._babylonGamepads[gamepad.index].isConnected) {
  71170. return;
  71171. }
  71172. }
  71173. var newGamepad;
  71174. if (_this._babylonGamepads[gamepad.index]) {
  71175. newGamepad = _this._babylonGamepads[gamepad.index];
  71176. newGamepad.browserGamepad = gamepad;
  71177. newGamepad._isConnected = true;
  71178. }
  71179. else {
  71180. newGamepad = _this._addNewGamepad(gamepad);
  71181. }
  71182. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71183. _this._startMonitoringGamepads();
  71184. };
  71185. this._onGamepadDisconnectedEvent = function (evt) {
  71186. var gamepad = evt.gamepad;
  71187. // Remove the gamepad from the list of gamepads to monitor.
  71188. for (var i in _this._babylonGamepads) {
  71189. if (_this._babylonGamepads[i].index === gamepad.index) {
  71190. var disconnectedGamepad = _this._babylonGamepads[i];
  71191. disconnectedGamepad._isConnected = false;
  71192. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  71193. break;
  71194. }
  71195. }
  71196. };
  71197. if (this._gamepadSupport) {
  71198. //first add already-connected gamepads
  71199. this._updateGamepadObjects();
  71200. if (this._babylonGamepads.length) {
  71201. this._startMonitoringGamepads();
  71202. }
  71203. // Checking if the gamepad connected event is supported (like in Firefox)
  71204. if (this._gamepadEventSupported) {
  71205. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  71206. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  71207. }
  71208. else {
  71209. this._startMonitoringGamepads();
  71210. }
  71211. }
  71212. }
  71213. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  71214. get: function () {
  71215. return this._babylonGamepads;
  71216. },
  71217. enumerable: true,
  71218. configurable: true
  71219. });
  71220. GamepadManager.prototype.getGamepadByType = function (type) {
  71221. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  71222. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  71223. var gamepad = _a[_i];
  71224. if (gamepad && gamepad.type === type) {
  71225. return gamepad;
  71226. }
  71227. }
  71228. return null;
  71229. };
  71230. GamepadManager.prototype.dispose = function () {
  71231. if (this._gamepadEventSupported) {
  71232. if (this._onGamepadConnectedEvent) {
  71233. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71234. }
  71235. if (this._onGamepadDisconnectedEvent) {
  71236. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71237. }
  71238. this._onGamepadConnectedEvent = null;
  71239. this._onGamepadDisconnectedEvent = null;
  71240. }
  71241. this._babylonGamepads.forEach(function (gamepad) {
  71242. gamepad.dispose();
  71243. });
  71244. this.onGamepadConnectedObservable.clear();
  71245. this.onGamepadDisconnectedObservable.clear();
  71246. this._oneGamepadConnected = false;
  71247. this._stopMonitoringGamepads();
  71248. this._babylonGamepads = [];
  71249. };
  71250. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71251. if (!this._oneGamepadConnected) {
  71252. this._oneGamepadConnected = true;
  71253. }
  71254. var newGamepad;
  71255. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71256. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71257. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71258. }
  71259. // if pose is supported, use the (WebVR) pose enabled controller
  71260. else if (gamepad.pose) {
  71261. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71262. }
  71263. else {
  71264. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71265. }
  71266. this._babylonGamepads[newGamepad.index] = newGamepad;
  71267. return newGamepad;
  71268. };
  71269. GamepadManager.prototype._startMonitoringGamepads = function () {
  71270. if (!this._isMonitoring) {
  71271. this._isMonitoring = true;
  71272. //back-comp
  71273. if (!this._scene) {
  71274. this._checkGamepadsStatus();
  71275. }
  71276. }
  71277. };
  71278. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71279. this._isMonitoring = false;
  71280. };
  71281. GamepadManager.prototype._checkGamepadsStatus = function () {
  71282. var _this = this;
  71283. // Hack to be compatible Chrome
  71284. this._updateGamepadObjects();
  71285. for (var i in this._babylonGamepads) {
  71286. var gamepad = this._babylonGamepads[i];
  71287. if (!gamepad || !gamepad.isConnected) {
  71288. continue;
  71289. }
  71290. gamepad.update();
  71291. }
  71292. if (this._isMonitoring && !this._scene) {
  71293. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71294. }
  71295. };
  71296. // This function is called only on Chrome, which does not properly support
  71297. // connection/disconnection events and forces you to recopy again the gamepad object
  71298. GamepadManager.prototype._updateGamepadObjects = function () {
  71299. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71300. for (var i = 0; i < gamepads.length; i++) {
  71301. var gamepad = gamepads[i];
  71302. if (gamepad) {
  71303. if (!this._babylonGamepads[gamepad.index]) {
  71304. var newGamepad = this._addNewGamepad(gamepad);
  71305. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71306. }
  71307. else {
  71308. // Forced to copy again this object for Chrome for unknown reason
  71309. this._babylonGamepads[i].browserGamepad = gamepad;
  71310. if (!this._babylonGamepads[i].isConnected) {
  71311. this._babylonGamepads[i]._isConnected = true;
  71312. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71313. }
  71314. }
  71315. }
  71316. }
  71317. };
  71318. return GamepadManager;
  71319. }());
  71320. BABYLON.GamepadManager = GamepadManager;
  71321. })(BABYLON || (BABYLON = {}));
  71322. //# sourceMappingURL=babylon.gamepadManager.js.map
  71323. var BABYLON;
  71324. (function (BABYLON) {
  71325. var StickValues = /** @class */ (function () {
  71326. function StickValues(x, y) {
  71327. this.x = x;
  71328. this.y = y;
  71329. }
  71330. return StickValues;
  71331. }());
  71332. BABYLON.StickValues = StickValues;
  71333. var Gamepad = /** @class */ (function () {
  71334. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71335. if (leftStickX === void 0) { leftStickX = 0; }
  71336. if (leftStickY === void 0) { leftStickY = 1; }
  71337. if (rightStickX === void 0) { rightStickX = 2; }
  71338. if (rightStickY === void 0) { rightStickY = 3; }
  71339. this.id = id;
  71340. this.index = index;
  71341. this.browserGamepad = browserGamepad;
  71342. this._isConnected = true;
  71343. this._invertLeftStickY = false;
  71344. this.type = Gamepad.GAMEPAD;
  71345. this._leftStickAxisX = leftStickX;
  71346. this._leftStickAxisY = leftStickY;
  71347. this._rightStickAxisX = rightStickX;
  71348. this._rightStickAxisY = rightStickY;
  71349. if (this.browserGamepad.axes.length >= 2) {
  71350. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71351. }
  71352. if (this.browserGamepad.axes.length >= 4) {
  71353. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71354. }
  71355. }
  71356. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71357. get: function () {
  71358. return this._isConnected;
  71359. },
  71360. enumerable: true,
  71361. configurable: true
  71362. });
  71363. Gamepad.prototype.onleftstickchanged = function (callback) {
  71364. this._onleftstickchanged = callback;
  71365. };
  71366. Gamepad.prototype.onrightstickchanged = function (callback) {
  71367. this._onrightstickchanged = callback;
  71368. };
  71369. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71370. get: function () {
  71371. return this._leftStick;
  71372. },
  71373. set: function (newValues) {
  71374. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71375. this._onleftstickchanged(newValues);
  71376. }
  71377. this._leftStick = newValues;
  71378. },
  71379. enumerable: true,
  71380. configurable: true
  71381. });
  71382. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71383. get: function () {
  71384. return this._rightStick;
  71385. },
  71386. set: function (newValues) {
  71387. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71388. this._onrightstickchanged(newValues);
  71389. }
  71390. this._rightStick = newValues;
  71391. },
  71392. enumerable: true,
  71393. configurable: true
  71394. });
  71395. Gamepad.prototype.update = function () {
  71396. if (this._leftStick) {
  71397. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71398. if (this._invertLeftStickY) {
  71399. this.leftStick.y *= -1;
  71400. }
  71401. }
  71402. if (this._rightStick) {
  71403. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71404. }
  71405. };
  71406. Gamepad.prototype.dispose = function () {
  71407. };
  71408. Gamepad.GAMEPAD = 0;
  71409. Gamepad.GENERIC = 1;
  71410. Gamepad.XBOX = 2;
  71411. Gamepad.POSE_ENABLED = 3;
  71412. return Gamepad;
  71413. }());
  71414. BABYLON.Gamepad = Gamepad;
  71415. var GenericPad = /** @class */ (function (_super) {
  71416. __extends(GenericPad, _super);
  71417. function GenericPad(id, index, browserGamepad) {
  71418. var _this = _super.call(this, id, index, browserGamepad) || this;
  71419. _this.onButtonDownObservable = new BABYLON.Observable();
  71420. _this.onButtonUpObservable = new BABYLON.Observable();
  71421. _this.type = Gamepad.GENERIC;
  71422. _this._buttons = new Array(browserGamepad.buttons.length);
  71423. return _this;
  71424. }
  71425. GenericPad.prototype.onbuttondown = function (callback) {
  71426. this._onbuttondown = callback;
  71427. };
  71428. GenericPad.prototype.onbuttonup = function (callback) {
  71429. this._onbuttonup = callback;
  71430. };
  71431. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71432. if (newValue !== currentValue) {
  71433. if (newValue === 1) {
  71434. if (this._onbuttondown) {
  71435. this._onbuttondown(buttonIndex);
  71436. }
  71437. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71438. }
  71439. if (newValue === 0) {
  71440. if (this._onbuttonup) {
  71441. this._onbuttonup(buttonIndex);
  71442. }
  71443. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71444. }
  71445. }
  71446. return newValue;
  71447. };
  71448. GenericPad.prototype.update = function () {
  71449. _super.prototype.update.call(this);
  71450. for (var index = 0; index < this._buttons.length; index++) {
  71451. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71452. }
  71453. };
  71454. GenericPad.prototype.dispose = function () {
  71455. _super.prototype.dispose.call(this);
  71456. this.onButtonDownObservable.clear();
  71457. this.onButtonUpObservable.clear();
  71458. };
  71459. return GenericPad;
  71460. }(Gamepad));
  71461. BABYLON.GenericPad = GenericPad;
  71462. })(BABYLON || (BABYLON = {}));
  71463. //# sourceMappingURL=babylon.gamepad.js.map
  71464. var BABYLON;
  71465. (function (BABYLON) {
  71466. /**
  71467. * Defines supported buttons for XBox360 compatible gamepads
  71468. */
  71469. var Xbox360Button;
  71470. (function (Xbox360Button) {
  71471. /** A */
  71472. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71473. /** B */
  71474. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71475. /** X */
  71476. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71477. /** Y */
  71478. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71479. /** Start */
  71480. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71481. /** Back */
  71482. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71483. /** Left button */
  71484. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71485. /** Right button */
  71486. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71487. /** Left stick */
  71488. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71489. /** Right stick */
  71490. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71491. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71492. /** Defines values for XBox360 DPad */
  71493. var Xbox360Dpad;
  71494. (function (Xbox360Dpad) {
  71495. /** Up */
  71496. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71497. /** Down */
  71498. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71499. /** Left */
  71500. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71501. /** Right */
  71502. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71503. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71504. /**
  71505. * Defines a XBox360 gamepad
  71506. */
  71507. var Xbox360Pad = /** @class */ (function (_super) {
  71508. __extends(Xbox360Pad, _super);
  71509. /**
  71510. * Creates a new XBox360 gamepad object
  71511. * @param id defines the id of this gamepad
  71512. * @param index defines its index
  71513. * @param gamepad defines the internal HTML gamepad object
  71514. * @param xboxOne defines if it is a XBox One gamepad
  71515. */
  71516. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71517. if (xboxOne === void 0) { xboxOne = false; }
  71518. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71519. _this._leftTrigger = 0;
  71520. _this._rightTrigger = 0;
  71521. /** Observable raised when a button is pressed */
  71522. _this.onButtonDownObservable = new BABYLON.Observable();
  71523. /** Observable raised when a button is released */
  71524. _this.onButtonUpObservable = new BABYLON.Observable();
  71525. /** Observable raised when a pad is pressed */
  71526. _this.onPadDownObservable = new BABYLON.Observable();
  71527. /** Observable raised when a pad is released */
  71528. _this.onPadUpObservable = new BABYLON.Observable();
  71529. _this._buttonA = 0;
  71530. _this._buttonB = 0;
  71531. _this._buttonX = 0;
  71532. _this._buttonY = 0;
  71533. _this._buttonBack = 0;
  71534. _this._buttonStart = 0;
  71535. _this._buttonLB = 0;
  71536. _this._buttonRB = 0;
  71537. _this._buttonLeftStick = 0;
  71538. _this._buttonRightStick = 0;
  71539. _this._dPadUp = 0;
  71540. _this._dPadDown = 0;
  71541. _this._dPadLeft = 0;
  71542. _this._dPadRight = 0;
  71543. _this._isXboxOnePad = false;
  71544. _this.type = BABYLON.Gamepad.XBOX;
  71545. _this._isXboxOnePad = xboxOne;
  71546. return _this;
  71547. }
  71548. /**
  71549. * Defines the callback to call when left trigger is pressed
  71550. * @param callback defines the callback to use
  71551. */
  71552. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71553. this._onlefttriggerchanged = callback;
  71554. };
  71555. /**
  71556. * Defines the callback to call when right trigger is pressed
  71557. * @param callback defines the callback to use
  71558. */
  71559. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71560. this._onrighttriggerchanged = callback;
  71561. };
  71562. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71563. /**
  71564. * Gets or sets left trigger value
  71565. */
  71566. get: function () {
  71567. return this._leftTrigger;
  71568. },
  71569. set: function (newValue) {
  71570. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71571. this._onlefttriggerchanged(newValue);
  71572. }
  71573. this._leftTrigger = newValue;
  71574. },
  71575. enumerable: true,
  71576. configurable: true
  71577. });
  71578. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71579. /**
  71580. * Gets or sets right trigger value
  71581. */
  71582. get: function () {
  71583. return this._rightTrigger;
  71584. },
  71585. set: function (newValue) {
  71586. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71587. this._onrighttriggerchanged(newValue);
  71588. }
  71589. this._rightTrigger = newValue;
  71590. },
  71591. enumerable: true,
  71592. configurable: true
  71593. });
  71594. /**
  71595. * Defines the callback to call when a button is pressed
  71596. * @param callback defines the callback to use
  71597. */
  71598. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71599. this._onbuttondown = callback;
  71600. };
  71601. /**
  71602. * Defines the callback to call when a button is released
  71603. * @param callback defines the callback to use
  71604. */
  71605. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71606. this._onbuttonup = callback;
  71607. };
  71608. /**
  71609. * Defines the callback to call when a pad is pressed
  71610. * @param callback defines the callback to use
  71611. */
  71612. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71613. this._ondpaddown = callback;
  71614. };
  71615. /**
  71616. * Defines the callback to call when a pad is released
  71617. * @param callback defines the callback to use
  71618. */
  71619. Xbox360Pad.prototype.ondpadup = function (callback) {
  71620. this._ondpadup = callback;
  71621. };
  71622. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71623. if (newValue !== currentValue) {
  71624. if (newValue === 1) {
  71625. if (this._onbuttondown) {
  71626. this._onbuttondown(buttonType);
  71627. }
  71628. this.onButtonDownObservable.notifyObservers(buttonType);
  71629. }
  71630. if (newValue === 0) {
  71631. if (this._onbuttonup) {
  71632. this._onbuttonup(buttonType);
  71633. }
  71634. this.onButtonUpObservable.notifyObservers(buttonType);
  71635. }
  71636. }
  71637. return newValue;
  71638. };
  71639. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71640. if (newValue !== currentValue) {
  71641. if (newValue === 1) {
  71642. if (this._ondpaddown) {
  71643. this._ondpaddown(buttonType);
  71644. }
  71645. this.onPadDownObservable.notifyObservers(buttonType);
  71646. }
  71647. if (newValue === 0) {
  71648. if (this._ondpadup) {
  71649. this._ondpadup(buttonType);
  71650. }
  71651. this.onPadUpObservable.notifyObservers(buttonType);
  71652. }
  71653. }
  71654. return newValue;
  71655. };
  71656. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71657. /** Gets or sets value of A button */
  71658. get: function () {
  71659. return this._buttonA;
  71660. },
  71661. set: function (value) {
  71662. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71663. },
  71664. enumerable: true,
  71665. configurable: true
  71666. });
  71667. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71668. /** Gets or sets value of B button */
  71669. get: function () {
  71670. return this._buttonB;
  71671. },
  71672. set: function (value) {
  71673. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71674. },
  71675. enumerable: true,
  71676. configurable: true
  71677. });
  71678. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71679. /** Gets or sets value of X button */
  71680. get: function () {
  71681. return this._buttonX;
  71682. },
  71683. set: function (value) {
  71684. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71685. },
  71686. enumerable: true,
  71687. configurable: true
  71688. });
  71689. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71690. /** Gets or sets value of Y button */
  71691. get: function () {
  71692. return this._buttonY;
  71693. },
  71694. set: function (value) {
  71695. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71696. },
  71697. enumerable: true,
  71698. configurable: true
  71699. });
  71700. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71701. /** Gets or sets value of Start button */
  71702. get: function () {
  71703. return this._buttonStart;
  71704. },
  71705. set: function (value) {
  71706. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71707. },
  71708. enumerable: true,
  71709. configurable: true
  71710. });
  71711. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71712. /** Gets or sets value of Back button */
  71713. get: function () {
  71714. return this._buttonBack;
  71715. },
  71716. set: function (value) {
  71717. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71718. },
  71719. enumerable: true,
  71720. configurable: true
  71721. });
  71722. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71723. /** Gets or sets value of Left button */
  71724. get: function () {
  71725. return this._buttonLB;
  71726. },
  71727. set: function (value) {
  71728. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71729. },
  71730. enumerable: true,
  71731. configurable: true
  71732. });
  71733. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71734. /** Gets or sets value of Right button */
  71735. get: function () {
  71736. return this._buttonRB;
  71737. },
  71738. set: function (value) {
  71739. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71740. },
  71741. enumerable: true,
  71742. configurable: true
  71743. });
  71744. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71745. /** Gets or sets value of left stick */
  71746. get: function () {
  71747. return this._buttonLeftStick;
  71748. },
  71749. set: function (value) {
  71750. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71751. },
  71752. enumerable: true,
  71753. configurable: true
  71754. });
  71755. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71756. /** Gets or sets value of right stick */
  71757. get: function () {
  71758. return this._buttonRightStick;
  71759. },
  71760. set: function (value) {
  71761. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71762. },
  71763. enumerable: true,
  71764. configurable: true
  71765. });
  71766. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71767. /** Gets or sets value of DPad up */
  71768. get: function () {
  71769. return this._dPadUp;
  71770. },
  71771. set: function (value) {
  71772. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71773. },
  71774. enumerable: true,
  71775. configurable: true
  71776. });
  71777. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71778. /** Gets or sets value of DPad down */
  71779. get: function () {
  71780. return this._dPadDown;
  71781. },
  71782. set: function (value) {
  71783. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71784. },
  71785. enumerable: true,
  71786. configurable: true
  71787. });
  71788. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71789. /** Gets or sets value of DPad left */
  71790. get: function () {
  71791. return this._dPadLeft;
  71792. },
  71793. set: function (value) {
  71794. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71795. },
  71796. enumerable: true,
  71797. configurable: true
  71798. });
  71799. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71800. /** Gets or sets value of DPad right */
  71801. get: function () {
  71802. return this._dPadRight;
  71803. },
  71804. set: function (value) {
  71805. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71806. },
  71807. enumerable: true,
  71808. configurable: true
  71809. });
  71810. /**
  71811. * Force the gamepad to synchronize with device values
  71812. */
  71813. Xbox360Pad.prototype.update = function () {
  71814. _super.prototype.update.call(this);
  71815. if (this._isXboxOnePad) {
  71816. this.buttonA = this.browserGamepad.buttons[0].value;
  71817. this.buttonB = this.browserGamepad.buttons[1].value;
  71818. this.buttonX = this.browserGamepad.buttons[2].value;
  71819. this.buttonY = this.browserGamepad.buttons[3].value;
  71820. this.buttonLB = this.browserGamepad.buttons[4].value;
  71821. this.buttonRB = this.browserGamepad.buttons[5].value;
  71822. this.leftTrigger = this.browserGamepad.axes[2];
  71823. this.rightTrigger = this.browserGamepad.axes[5];
  71824. this.buttonBack = this.browserGamepad.buttons[9].value;
  71825. this.buttonStart = this.browserGamepad.buttons[8].value;
  71826. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71827. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71828. this.dPadUp = this.browserGamepad.buttons[11].value;
  71829. this.dPadDown = this.browserGamepad.buttons[12].value;
  71830. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71831. this.dPadRight = this.browserGamepad.buttons[14].value;
  71832. }
  71833. else {
  71834. this.buttonA = this.browserGamepad.buttons[0].value;
  71835. this.buttonB = this.browserGamepad.buttons[1].value;
  71836. this.buttonX = this.browserGamepad.buttons[2].value;
  71837. this.buttonY = this.browserGamepad.buttons[3].value;
  71838. this.buttonLB = this.browserGamepad.buttons[4].value;
  71839. this.buttonRB = this.browserGamepad.buttons[5].value;
  71840. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71841. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71842. this.buttonBack = this.browserGamepad.buttons[8].value;
  71843. this.buttonStart = this.browserGamepad.buttons[9].value;
  71844. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71845. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71846. this.dPadUp = this.browserGamepad.buttons[12].value;
  71847. this.dPadDown = this.browserGamepad.buttons[13].value;
  71848. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71849. this.dPadRight = this.browserGamepad.buttons[15].value;
  71850. }
  71851. };
  71852. Xbox360Pad.prototype.dispose = function () {
  71853. _super.prototype.dispose.call(this);
  71854. this.onButtonDownObservable.clear();
  71855. this.onButtonUpObservable.clear();
  71856. this.onPadDownObservable.clear();
  71857. this.onPadUpObservable.clear();
  71858. };
  71859. return Xbox360Pad;
  71860. }(BABYLON.Gamepad));
  71861. BABYLON.Xbox360Pad = Xbox360Pad;
  71862. })(BABYLON || (BABYLON = {}));
  71863. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71864. var BABYLON;
  71865. (function (BABYLON) {
  71866. /**
  71867. * Defines the types of pose enabled controllers that are supported
  71868. */
  71869. var PoseEnabledControllerType;
  71870. (function (PoseEnabledControllerType) {
  71871. /**
  71872. * HTC Vive
  71873. */
  71874. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71875. /**
  71876. * Oculus Rift
  71877. */
  71878. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71879. /**
  71880. * Windows mixed reality
  71881. */
  71882. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71883. /**
  71884. * Samsung gear VR
  71885. */
  71886. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71887. /**
  71888. * Google Daydream
  71889. */
  71890. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71891. /**
  71892. * Generic
  71893. */
  71894. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71895. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71896. /**
  71897. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71898. */
  71899. var PoseEnabledControllerHelper = /** @class */ (function () {
  71900. function PoseEnabledControllerHelper() {
  71901. }
  71902. /**
  71903. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71904. * @param vrGamepad the gamepad to initialized
  71905. * @returns a vr controller of the type the gamepad identified as
  71906. */
  71907. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71908. // Oculus Touch
  71909. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71910. return new BABYLON.OculusTouchController(vrGamepad);
  71911. }
  71912. // Windows Mixed Reality controllers
  71913. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71914. return new BABYLON.WindowsMotionController(vrGamepad);
  71915. }
  71916. // HTC Vive
  71917. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71918. return new BABYLON.ViveController(vrGamepad);
  71919. }
  71920. // Samsung/Oculus Gear VR or Oculus Go
  71921. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71922. return new BABYLON.GearVRController(vrGamepad);
  71923. }
  71924. // Google Daydream
  71925. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71926. return new BABYLON.DaydreamController(vrGamepad);
  71927. }
  71928. // Generic
  71929. else {
  71930. return new BABYLON.GenericController(vrGamepad);
  71931. }
  71932. };
  71933. return PoseEnabledControllerHelper;
  71934. }());
  71935. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71936. /**
  71937. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71938. */
  71939. var PoseEnabledController = /** @class */ (function (_super) {
  71940. __extends(PoseEnabledController, _super);
  71941. /**
  71942. * Creates a new PoseEnabledController from a gamepad
  71943. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71944. */
  71945. function PoseEnabledController(browserGamepad) {
  71946. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71947. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71948. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71949. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71950. /**
  71951. * The device position in babylon space
  71952. */
  71953. _this.devicePosition = BABYLON.Vector3.Zero();
  71954. /**
  71955. * The device rotation in babylon space
  71956. */
  71957. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71958. /**
  71959. * The scale factor of the device in babylon space
  71960. */
  71961. _this.deviceScaleFactor = 1;
  71962. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71963. /**
  71964. * Internal, matrix used to convert room space to babylon space
  71965. */
  71966. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71967. /**
  71968. * Node to be used when casting a ray from the controller
  71969. */
  71970. _this._pointingPoseNode = null;
  71971. _this._workingMatrix = BABYLON.Matrix.Identity();
  71972. /**
  71973. * @hidden
  71974. */
  71975. _this._meshAttachedObservable = new BABYLON.Observable();
  71976. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71977. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71978. _this.position = BABYLON.Vector3.Zero();
  71979. _this.rotationQuaternion = new BABYLON.Quaternion();
  71980. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71981. _this._calculatedRotation = new BABYLON.Quaternion();
  71982. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71983. return _this;
  71984. }
  71985. /**
  71986. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71987. */
  71988. PoseEnabledController.prototype.update = function () {
  71989. _super.prototype.update.call(this);
  71990. this._updatePoseAndMesh();
  71991. };
  71992. /**
  71993. * Updates only the pose device and mesh without doing any button event checking
  71994. */
  71995. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71996. var pose = this.browserGamepad.pose;
  71997. this.updateFromDevice(pose);
  71998. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71999. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  72000. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72001. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  72002. if (this._mesh) {
  72003. this._mesh.position.copyFrom(this.devicePosition);
  72004. if (this._mesh.rotationQuaternion) {
  72005. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  72006. }
  72007. }
  72008. };
  72009. /**
  72010. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  72011. * @param poseData raw pose fromthe device
  72012. */
  72013. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  72014. if (poseData) {
  72015. this.rawPose = poseData;
  72016. if (poseData.position) {
  72017. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  72018. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  72019. this._deviceRoomPosition.z *= -1;
  72020. }
  72021. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  72022. this._calculatedPosition.addInPlace(this.position);
  72023. }
  72024. var pose = this.rawPose;
  72025. if (poseData.orientation && pose.orientation) {
  72026. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  72027. if (this._mesh) {
  72028. if (this._mesh.getScene().useRightHandedSystem) {
  72029. this._deviceRoomRotationQuaternion.z *= -1;
  72030. this._deviceRoomRotationQuaternion.w *= -1;
  72031. }
  72032. else {
  72033. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  72034. }
  72035. }
  72036. // if the camera is set, rotate to the camera's rotation
  72037. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  72038. }
  72039. }
  72040. };
  72041. /**
  72042. * Attaches a mesh to the controller
  72043. * @param mesh the mesh to be attached
  72044. */
  72045. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  72046. if (this._mesh) {
  72047. this._mesh.parent = null;
  72048. }
  72049. this._mesh = mesh;
  72050. if (this._poseControlledCamera) {
  72051. this._mesh.parent = this._poseControlledCamera;
  72052. }
  72053. if (!this._mesh.rotationQuaternion) {
  72054. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  72055. }
  72056. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  72057. this._updatePoseAndMesh();
  72058. if (this._pointingPoseNode) {
  72059. var parents = [];
  72060. var obj = this._pointingPoseNode;
  72061. while (obj.parent) {
  72062. parents.push(obj.parent);
  72063. obj = obj.parent;
  72064. }
  72065. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  72066. }
  72067. this._meshAttachedObservable.notifyObservers(mesh);
  72068. };
  72069. /**
  72070. * Attaches the controllers mesh to a camera
  72071. * @param camera the camera the mesh should be attached to
  72072. */
  72073. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  72074. this._poseControlledCamera = camera;
  72075. if (this._mesh) {
  72076. this._mesh.parent = this._poseControlledCamera;
  72077. }
  72078. };
  72079. /**
  72080. * Disposes of the controller
  72081. */
  72082. PoseEnabledController.prototype.dispose = function () {
  72083. if (this._mesh) {
  72084. this._mesh.dispose();
  72085. }
  72086. this._mesh = null;
  72087. _super.prototype.dispose.call(this);
  72088. };
  72089. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  72090. /**
  72091. * The mesh that is attached to the controller
  72092. */
  72093. get: function () {
  72094. return this._mesh;
  72095. },
  72096. enumerable: true,
  72097. configurable: true
  72098. });
  72099. /**
  72100. * Gets the ray of the controller in the direction the controller is pointing
  72101. * @param length the length the resulting ray should be
  72102. * @returns a ray in the direction the controller is pointing
  72103. */
  72104. PoseEnabledController.prototype.getForwardRay = function (length) {
  72105. if (length === void 0) { length = 100; }
  72106. if (!this.mesh) {
  72107. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  72108. }
  72109. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  72110. var origin = m.getTranslation();
  72111. var forward = new BABYLON.Vector3(0, 0, -1);
  72112. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72113. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72114. return new BABYLON.Ray(origin, direction, length);
  72115. };
  72116. /**
  72117. * Name of the child mesh that can be used to cast a ray from the controller
  72118. */
  72119. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  72120. return PoseEnabledController;
  72121. }(BABYLON.Gamepad));
  72122. BABYLON.PoseEnabledController = PoseEnabledController;
  72123. })(BABYLON || (BABYLON = {}));
  72124. //# sourceMappingURL=babylon.poseEnabledController.js.map
  72125. var BABYLON;
  72126. (function (BABYLON) {
  72127. /**
  72128. * Defines the WebVRController object that represents controllers tracked in 3D space
  72129. */
  72130. var WebVRController = /** @class */ (function (_super) {
  72131. __extends(WebVRController, _super);
  72132. /**
  72133. * Creates a new WebVRController from a gamepad
  72134. * @param vrGamepad the gamepad that the WebVRController should be created from
  72135. */
  72136. function WebVRController(vrGamepad) {
  72137. var _this = _super.call(this, vrGamepad) || this;
  72138. // Observables
  72139. /**
  72140. * Fired when the trigger state has changed
  72141. */
  72142. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  72143. /**
  72144. * Fired when the main button state has changed
  72145. */
  72146. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  72147. /**
  72148. * Fired when the secondary button state has changed
  72149. */
  72150. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  72151. /**
  72152. * Fired when the pad state has changed
  72153. */
  72154. _this.onPadStateChangedObservable = new BABYLON.Observable();
  72155. /**
  72156. * Fired when controllers stick values have changed
  72157. */
  72158. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  72159. /**
  72160. * X and Y axis corrisponding to the controllers joystick
  72161. */
  72162. _this.pad = { x: 0, y: 0 };
  72163. // avoid GC, store state in a tmp object
  72164. _this._changes = {
  72165. pressChanged: false,
  72166. touchChanged: false,
  72167. valueChanged: false,
  72168. changed: false
  72169. };
  72170. _this._buttons = new Array(vrGamepad.buttons.length);
  72171. _this.hand = vrGamepad.hand;
  72172. return _this;
  72173. }
  72174. /**
  72175. * Fired when a controller button's state has changed
  72176. * @param callback the callback containing the button that was modified
  72177. */
  72178. WebVRController.prototype.onButtonStateChange = function (callback) {
  72179. this._onButtonStateChange = callback;
  72180. };
  72181. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  72182. /**
  72183. * The default controller model for the controller
  72184. */
  72185. get: function () {
  72186. return this._defaultModel;
  72187. },
  72188. enumerable: true,
  72189. configurable: true
  72190. });
  72191. /**
  72192. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  72193. */
  72194. WebVRController.prototype.update = function () {
  72195. _super.prototype.update.call(this);
  72196. for (var index = 0; index < this._buttons.length; index++) {
  72197. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  72198. }
  72199. ;
  72200. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  72201. this.pad.x = this.leftStick.x;
  72202. this.pad.y = this.leftStick.y;
  72203. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  72204. }
  72205. };
  72206. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  72207. if (!newState) {
  72208. newState = {
  72209. pressed: false,
  72210. touched: false,
  72211. value: 0
  72212. };
  72213. }
  72214. if (!currentState) {
  72215. this._buttons[buttonIndex] = {
  72216. pressed: newState.pressed,
  72217. touched: newState.touched,
  72218. value: newState.value
  72219. };
  72220. return;
  72221. }
  72222. this._checkChanges(newState, currentState);
  72223. if (this._changes.changed) {
  72224. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  72225. this._handleButtonChange(buttonIndex, newState, this._changes);
  72226. }
  72227. this._buttons[buttonIndex].pressed = newState.pressed;
  72228. this._buttons[buttonIndex].touched = newState.touched;
  72229. // oculus triggers are never 0, thou not touched.
  72230. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  72231. };
  72232. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72233. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72234. this._changes.touchChanged = newState.touched !== currentState.touched;
  72235. this._changes.valueChanged = newState.value !== currentState.value;
  72236. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72237. return this._changes;
  72238. };
  72239. /**
  72240. * Disposes of th webVRCOntroller
  72241. */
  72242. WebVRController.prototype.dispose = function () {
  72243. _super.prototype.dispose.call(this);
  72244. this.onTriggerStateChangedObservable.clear();
  72245. this.onMainButtonStateChangedObservable.clear();
  72246. this.onSecondaryButtonStateChangedObservable.clear();
  72247. this.onPadStateChangedObservable.clear();
  72248. this.onPadValuesChangedObservable.clear();
  72249. };
  72250. return WebVRController;
  72251. }(BABYLON.PoseEnabledController));
  72252. BABYLON.WebVRController = WebVRController;
  72253. })(BABYLON || (BABYLON = {}));
  72254. //# sourceMappingURL=babylon.webVRController.js.map
  72255. var BABYLON;
  72256. (function (BABYLON) {
  72257. /**
  72258. * Oculus Touch Controller
  72259. */
  72260. var OculusTouchController = /** @class */ (function (_super) {
  72261. __extends(OculusTouchController, _super);
  72262. /**
  72263. * Creates a new OculusTouchController from a gamepad
  72264. * @param vrGamepad the gamepad that the controller should be created from
  72265. */
  72266. function OculusTouchController(vrGamepad) {
  72267. var _this = _super.call(this, vrGamepad) || this;
  72268. /**
  72269. * Fired when the secondary trigger on this controller is modified
  72270. */
  72271. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72272. /**
  72273. * Fired when the thumb rest on this controller is modified
  72274. */
  72275. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72276. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72277. return _this;
  72278. }
  72279. /**
  72280. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72281. * @param scene scene in which to add meshes
  72282. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72283. */
  72284. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72285. var _this = this;
  72286. var meshName;
  72287. // Hand
  72288. if (this.hand === 'left') {
  72289. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72290. }
  72291. else { // Right is the default if no hand is specified
  72292. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72293. }
  72294. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72295. /*
  72296. Parent Mesh name: oculus_touch_left
  72297. - body
  72298. - trigger
  72299. - thumbstick
  72300. - grip
  72301. - button_y
  72302. - button_x
  72303. - button_enter
  72304. */
  72305. _this._defaultModel = newMeshes[1];
  72306. _this.attachToMesh(_this._defaultModel);
  72307. if (meshLoaded) {
  72308. meshLoaded(_this._defaultModel);
  72309. }
  72310. });
  72311. };
  72312. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72313. /**
  72314. * Fired when the A button on this controller is modified
  72315. */
  72316. get: function () {
  72317. if (this.hand === 'right') {
  72318. return this.onMainButtonStateChangedObservable;
  72319. }
  72320. else {
  72321. throw new Error('No A button on left hand');
  72322. }
  72323. },
  72324. enumerable: true,
  72325. configurable: true
  72326. });
  72327. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72328. /**
  72329. * Fired when the B button on this controller is modified
  72330. */
  72331. get: function () {
  72332. if (this.hand === 'right') {
  72333. return this.onSecondaryButtonStateChangedObservable;
  72334. }
  72335. else {
  72336. throw new Error('No B button on left hand');
  72337. }
  72338. },
  72339. enumerable: true,
  72340. configurable: true
  72341. });
  72342. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72343. /**
  72344. * Fired when the X button on this controller is modified
  72345. */
  72346. get: function () {
  72347. if (this.hand === 'left') {
  72348. return this.onMainButtonStateChangedObservable;
  72349. }
  72350. else {
  72351. throw new Error('No X button on right hand');
  72352. }
  72353. },
  72354. enumerable: true,
  72355. configurable: true
  72356. });
  72357. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72358. /**
  72359. * Fired when the Y button on this controller is modified
  72360. */
  72361. get: function () {
  72362. if (this.hand === 'left') {
  72363. return this.onSecondaryButtonStateChangedObservable;
  72364. }
  72365. else {
  72366. throw new Error('No Y button on right hand');
  72367. }
  72368. },
  72369. enumerable: true,
  72370. configurable: true
  72371. });
  72372. /**
  72373. * Called once for each button that changed state since the last frame
  72374. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72375. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72376. * 2) secondary trigger (same)
  72377. * 3) A (right) X (left), touch, pressed = value
  72378. * 4) B / Y
  72379. * 5) thumb rest
  72380. * @param buttonIdx Which button index changed
  72381. * @param state New state of the button
  72382. * @param changes Which properties on the state changed since last frame
  72383. */
  72384. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72385. var notifyObject = state; //{ state: state, changes: changes };
  72386. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72387. switch (buttonIdx) {
  72388. case 0:
  72389. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72390. return;
  72391. case 1: // index trigger
  72392. if (this._defaultModel) {
  72393. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72394. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72395. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72396. }
  72397. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72398. return;
  72399. case 2: // secondary trigger
  72400. if (this._defaultModel) {
  72401. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72402. }
  72403. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72404. return;
  72405. case 3:
  72406. if (this._defaultModel) {
  72407. if (notifyObject.pressed) {
  72408. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72409. }
  72410. else {
  72411. (this._defaultModel.getChildren()[1]).position.y = 0;
  72412. }
  72413. }
  72414. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72415. return;
  72416. case 4:
  72417. if (this._defaultModel) {
  72418. if (notifyObject.pressed) {
  72419. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72420. }
  72421. else {
  72422. (this._defaultModel.getChildren()[2]).position.y = 0;
  72423. }
  72424. }
  72425. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72426. return;
  72427. case 5:
  72428. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72429. return;
  72430. }
  72431. };
  72432. /**
  72433. * Base Url for the controller model.
  72434. */
  72435. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72436. /**
  72437. * File name for the left controller model.
  72438. */
  72439. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72440. /**
  72441. * File name for the right controller model.
  72442. */
  72443. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72444. return OculusTouchController;
  72445. }(BABYLON.WebVRController));
  72446. BABYLON.OculusTouchController = OculusTouchController;
  72447. })(BABYLON || (BABYLON = {}));
  72448. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72449. var BABYLON;
  72450. (function (BABYLON) {
  72451. /**
  72452. * Vive Controller
  72453. */
  72454. var ViveController = /** @class */ (function (_super) {
  72455. __extends(ViveController, _super);
  72456. /**
  72457. * Creates a new ViveController from a gamepad
  72458. * @param vrGamepad the gamepad that the controller should be created from
  72459. */
  72460. function ViveController(vrGamepad) {
  72461. var _this = _super.call(this, vrGamepad) || this;
  72462. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72463. _this._invertLeftStickY = true;
  72464. return _this;
  72465. }
  72466. /**
  72467. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72468. * @param scene scene in which to add meshes
  72469. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72470. */
  72471. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72472. var _this = this;
  72473. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72474. /*
  72475. Parent Mesh name: ViveWand
  72476. - body
  72477. - r_gripper
  72478. - l_gripper
  72479. - menu_button
  72480. - system_button
  72481. - trackpad
  72482. - trigger
  72483. - LED
  72484. */
  72485. _this._defaultModel = newMeshes[1];
  72486. _this.attachToMesh(_this._defaultModel);
  72487. if (meshLoaded) {
  72488. meshLoaded(_this._defaultModel);
  72489. }
  72490. });
  72491. };
  72492. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72493. /**
  72494. * Fired when the left button on this controller is modified
  72495. */
  72496. get: function () {
  72497. return this.onMainButtonStateChangedObservable;
  72498. },
  72499. enumerable: true,
  72500. configurable: true
  72501. });
  72502. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72503. /**
  72504. * Fired when the right button on this controller is modified
  72505. */
  72506. get: function () {
  72507. return this.onMainButtonStateChangedObservable;
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72513. /**
  72514. * Fired when the menu button on this controller is modified
  72515. */
  72516. get: function () {
  72517. return this.onSecondaryButtonStateChangedObservable;
  72518. },
  72519. enumerable: true,
  72520. configurable: true
  72521. });
  72522. /**
  72523. * Called once for each button that changed state since the last frame
  72524. * Vive mapping:
  72525. * 0: touchpad
  72526. * 1: trigger
  72527. * 2: left AND right buttons
  72528. * 3: menu button
  72529. * @param buttonIdx Which button index changed
  72530. * @param state New state of the button
  72531. * @param changes Which properties on the state changed since last frame
  72532. */
  72533. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72534. var notifyObject = state; //{ state: state, changes: changes };
  72535. switch (buttonIdx) {
  72536. case 0:
  72537. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72538. return;
  72539. case 1: // index trigger
  72540. if (this._defaultModel) {
  72541. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72542. }
  72543. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72544. return;
  72545. case 2: // left AND right button
  72546. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72547. return;
  72548. case 3:
  72549. if (this._defaultModel) {
  72550. if (notifyObject.pressed) {
  72551. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72552. }
  72553. else {
  72554. (this._defaultModel.getChildren()[2]).position.y = 0;
  72555. }
  72556. }
  72557. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72558. return;
  72559. }
  72560. };
  72561. /**
  72562. * Base Url for the controller model.
  72563. */
  72564. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72565. /**
  72566. * File name for the controller model.
  72567. */
  72568. ViveController.MODEL_FILENAME = 'wand.babylon';
  72569. return ViveController;
  72570. }(BABYLON.WebVRController));
  72571. BABYLON.ViveController = ViveController;
  72572. })(BABYLON || (BABYLON = {}));
  72573. //# sourceMappingURL=babylon.viveController.js.map
  72574. var BABYLON;
  72575. (function (BABYLON) {
  72576. /**
  72577. * Generic Controller
  72578. */
  72579. var GenericController = /** @class */ (function (_super) {
  72580. __extends(GenericController, _super);
  72581. /**
  72582. * Creates a new GenericController from a gamepad
  72583. * @param vrGamepad the gamepad that the controller should be created from
  72584. */
  72585. function GenericController(vrGamepad) {
  72586. return _super.call(this, vrGamepad) || this;
  72587. }
  72588. /**
  72589. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72590. * @param scene scene in which to add meshes
  72591. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72592. */
  72593. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72594. var _this = this;
  72595. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72596. _this._defaultModel = newMeshes[1];
  72597. _this.attachToMesh(_this._defaultModel);
  72598. if (meshLoaded) {
  72599. meshLoaded(_this._defaultModel);
  72600. }
  72601. });
  72602. };
  72603. /**
  72604. * Called once for each button that changed state since the last frame
  72605. * @param buttonIdx Which button index changed
  72606. * @param state New state of the button
  72607. * @param changes Which properties on the state changed since last frame
  72608. */
  72609. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72610. console.log("Button id: " + buttonIdx + "state: ");
  72611. console.dir(state);
  72612. };
  72613. /**
  72614. * Base Url for the controller model.
  72615. */
  72616. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72617. /**
  72618. * File name for the controller model.
  72619. */
  72620. GenericController.MODEL_FILENAME = 'generic.babylon';
  72621. return GenericController;
  72622. }(BABYLON.WebVRController));
  72623. BABYLON.GenericController = GenericController;
  72624. })(BABYLON || (BABYLON = {}));
  72625. //# sourceMappingURL=babylon.genericController.js.map
  72626. var BABYLON;
  72627. (function (BABYLON) {
  72628. /**
  72629. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72630. */
  72631. var LoadedMeshInfo = /** @class */ (function () {
  72632. function LoadedMeshInfo() {
  72633. /**
  72634. * Map of the button meshes contained in the controller
  72635. */
  72636. this.buttonMeshes = {};
  72637. /**
  72638. * Map of the axis meshes contained in the controller
  72639. */
  72640. this.axisMeshes = {};
  72641. }
  72642. return LoadedMeshInfo;
  72643. }());
  72644. /**
  72645. * Defines the WindowsMotionController object that the state of the windows motion controller
  72646. */
  72647. var WindowsMotionController = /** @class */ (function (_super) {
  72648. __extends(WindowsMotionController, _super);
  72649. /**
  72650. * Creates a new WindowsMotionController from a gamepad
  72651. * @param vrGamepad the gamepad that the controller should be created from
  72652. */
  72653. function WindowsMotionController(vrGamepad) {
  72654. var _this = _super.call(this, vrGamepad) || this;
  72655. _this._mapping = {
  72656. // Semantic button names
  72657. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72658. // A mapping of the button name to glTF model node name
  72659. // that should be transformed by button value.
  72660. buttonMeshNames: {
  72661. 'trigger': 'SELECT',
  72662. 'menu': 'MENU',
  72663. 'grip': 'GRASP',
  72664. 'thumbstick': 'THUMBSTICK_PRESS',
  72665. 'trackpad': 'TOUCHPAD_PRESS'
  72666. },
  72667. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72668. buttonObservableNames: {
  72669. 'trigger': 'onTriggerStateChangedObservable',
  72670. 'menu': 'onSecondaryButtonStateChangedObservable',
  72671. 'grip': 'onMainButtonStateChangedObservable',
  72672. 'thumbstick': 'onPadStateChangedObservable',
  72673. 'trackpad': 'onTrackpadChangedObservable'
  72674. },
  72675. // A mapping of the axis name to glTF model node name
  72676. // that should be transformed by axis value.
  72677. // This array mirrors the browserGamepad.axes array, such that
  72678. // the mesh corresponding to axis 0 is in this array index 0.
  72679. axisMeshNames: [
  72680. 'THUMBSTICK_X',
  72681. 'THUMBSTICK_Y',
  72682. 'TOUCHPAD_TOUCH_X',
  72683. 'TOUCHPAD_TOUCH_Y'
  72684. ],
  72685. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72686. };
  72687. /**
  72688. * Fired when the trackpad on this controller is clicked
  72689. */
  72690. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72691. /**
  72692. * Fired when the trackpad on this controller is modified
  72693. */
  72694. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72695. /**
  72696. * The current x and y values of this controller's trackpad
  72697. */
  72698. _this.trackpad = { x: 0, y: 0 };
  72699. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72700. _this._loadedMeshInfo = null;
  72701. return _this;
  72702. }
  72703. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72704. /**
  72705. * Fired when the trigger on this controller is modified
  72706. */
  72707. get: function () {
  72708. return this.onTriggerStateChangedObservable;
  72709. },
  72710. enumerable: true,
  72711. configurable: true
  72712. });
  72713. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72714. /**
  72715. * Fired when the menu button on this controller is modified
  72716. */
  72717. get: function () {
  72718. return this.onSecondaryButtonStateChangedObservable;
  72719. },
  72720. enumerable: true,
  72721. configurable: true
  72722. });
  72723. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72724. /**
  72725. * Fired when the grip button on this controller is modified
  72726. */
  72727. get: function () {
  72728. return this.onMainButtonStateChangedObservable;
  72729. },
  72730. enumerable: true,
  72731. configurable: true
  72732. });
  72733. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72734. /**
  72735. * Fired when the thumbstick button on this controller is modified
  72736. */
  72737. get: function () {
  72738. return this.onPadStateChangedObservable;
  72739. },
  72740. enumerable: true,
  72741. configurable: true
  72742. });
  72743. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72744. /**
  72745. * Fired when the touchpad button on this controller is modified
  72746. */
  72747. get: function () {
  72748. return this.onTrackpadChangedObservable;
  72749. },
  72750. enumerable: true,
  72751. configurable: true
  72752. });
  72753. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72754. /**
  72755. * Fired when the touchpad values on this controller are modified
  72756. */
  72757. get: function () {
  72758. return this.onTrackpadValuesChangedObservable;
  72759. },
  72760. enumerable: true,
  72761. configurable: true
  72762. });
  72763. WindowsMotionController.prototype._updateTrackpad = function () {
  72764. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72765. this.trackpad.x = this.browserGamepad["axes"][2];
  72766. this.trackpad.y = this.browserGamepad["axes"][3];
  72767. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72768. }
  72769. };
  72770. /**
  72771. * Called once per frame by the engine.
  72772. */
  72773. WindowsMotionController.prototype.update = function () {
  72774. _super.prototype.update.call(this);
  72775. if (this.browserGamepad.axes) {
  72776. this._updateTrackpad();
  72777. // Only need to animate axes if there is a loaded mesh
  72778. if (this._loadedMeshInfo) {
  72779. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72780. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72781. }
  72782. }
  72783. }
  72784. };
  72785. /**
  72786. * Called once for each button that changed state since the last frame
  72787. * @param buttonIdx Which button index changed
  72788. * @param state New state of the button
  72789. * @param changes Which properties on the state changed since last frame
  72790. */
  72791. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72792. var buttonName = this._mapping.buttons[buttonIdx];
  72793. if (!buttonName) {
  72794. return;
  72795. }
  72796. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72797. this._updateTrackpad();
  72798. // Only emit events for buttons that we know how to map from index to name
  72799. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72800. if (observable) {
  72801. observable.notifyObservers(state);
  72802. }
  72803. this._lerpButtonTransform(buttonName, state.value);
  72804. };
  72805. /**
  72806. * Moves the buttons on the controller mesh based on their current state
  72807. * @param buttonName the name of the button to move
  72808. * @param buttonValue the value of the button which determines the buttons new position
  72809. */
  72810. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72811. // If there is no loaded mesh, there is nothing to transform.
  72812. if (!this._loadedMeshInfo) {
  72813. return;
  72814. }
  72815. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72816. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72817. return;
  72818. }
  72819. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72820. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72821. };
  72822. /**
  72823. * Moves the axis on the controller mesh based on its current state
  72824. * @param axis the index of the axis
  72825. * @param axisValue the value of the axis which determines the meshes new position
  72826. * @hidden
  72827. */
  72828. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72829. if (!this._loadedMeshInfo) {
  72830. return;
  72831. }
  72832. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72833. if (!meshInfo) {
  72834. return;
  72835. }
  72836. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72837. return;
  72838. }
  72839. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72840. var lerpValue = axisValue * 0.5 + 0.5;
  72841. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72842. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72843. };
  72844. /**
  72845. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72846. * @param scene scene in which to add meshes
  72847. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72848. */
  72849. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72850. var _this = this;
  72851. if (forceDefault === void 0) { forceDefault = false; }
  72852. var path;
  72853. var filename;
  72854. // Checking if GLB loader is present
  72855. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72856. // Determine the device specific folder based on the ID suffix
  72857. var device = 'default';
  72858. if (this.id && !forceDefault) {
  72859. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72860. device = ((match && match[0]) || device);
  72861. }
  72862. // Hand
  72863. if (this.hand === 'left') {
  72864. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72865. }
  72866. else { // Right is the default if no hand is specified
  72867. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72868. }
  72869. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72870. }
  72871. else {
  72872. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72873. path = BABYLON.GenericController.MODEL_BASE_URL;
  72874. filename = BABYLON.GenericController.MODEL_FILENAME;
  72875. }
  72876. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72877. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72878. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72879. if (!_this._loadedMeshInfo) {
  72880. return;
  72881. }
  72882. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72883. _this.attachToMesh(_this._defaultModel);
  72884. if (meshLoaded) {
  72885. meshLoaded(_this._defaultModel);
  72886. }
  72887. }, null, function (scene, message) {
  72888. BABYLON.Tools.Log(message);
  72889. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72890. if (!forceDefault) {
  72891. _this.initControllerMesh(scene, meshLoaded, true);
  72892. }
  72893. });
  72894. };
  72895. /**
  72896. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72897. * can be transformed by button presses and axes values, based on this._mapping.
  72898. *
  72899. * @param scene scene in which the meshes exist
  72900. * @param meshes list of meshes that make up the controller model to process
  72901. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72902. */
  72903. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72904. var loadedMeshInfo = null;
  72905. // Create a new mesh to contain the glTF hierarchy
  72906. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72907. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72908. var childMesh = null;
  72909. for (var i = 0; i < meshes.length; i++) {
  72910. var mesh = meshes[i];
  72911. if (!mesh.parent) {
  72912. // Exclude controller meshes from picking results
  72913. mesh.isPickable = false;
  72914. // Handle root node, attach to the new parentMesh
  72915. childMesh = mesh;
  72916. break;
  72917. }
  72918. }
  72919. if (childMesh) {
  72920. childMesh.setParent(parentMesh);
  72921. // Create our mesh info. Note that this method will always return non-null.
  72922. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72923. }
  72924. else {
  72925. BABYLON.Tools.Warn('Could not find root node in model file.');
  72926. }
  72927. return loadedMeshInfo;
  72928. };
  72929. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72930. var loadedMeshInfo = new LoadedMeshInfo();
  72931. var i;
  72932. loadedMeshInfo.rootNode = rootNode;
  72933. // Reset the caches
  72934. loadedMeshInfo.buttonMeshes = {};
  72935. loadedMeshInfo.axisMeshes = {};
  72936. // Button Meshes
  72937. for (i = 0; i < this._mapping.buttons.length; i++) {
  72938. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72939. if (!buttonMeshName) {
  72940. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72941. continue;
  72942. }
  72943. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72944. if (!buttonMesh) {
  72945. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72946. continue;
  72947. }
  72948. var buttonMeshInfo = {
  72949. index: i,
  72950. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72951. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72952. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72953. };
  72954. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72955. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72956. }
  72957. else {
  72958. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72959. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72960. '(VALUE: ' + !!buttonMeshInfo.value +
  72961. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72962. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72963. ')');
  72964. }
  72965. }
  72966. // Axis Meshes
  72967. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72968. var axisMeshName = this._mapping.axisMeshNames[i];
  72969. if (!axisMeshName) {
  72970. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72971. continue;
  72972. }
  72973. var axisMesh = getChildByName(rootNode, axisMeshName);
  72974. if (!axisMesh) {
  72975. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72976. continue;
  72977. }
  72978. var axisMeshInfo = {
  72979. index: i,
  72980. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72981. min: getImmediateChildByName(axisMesh, 'MIN'),
  72982. max: getImmediateChildByName(axisMesh, 'MAX')
  72983. };
  72984. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72985. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72986. }
  72987. else {
  72988. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72989. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72990. '(VALUE: ' + !!axisMeshInfo.value +
  72991. ', MIN: ' + !!axisMeshInfo.min +
  72992. ', MAX:' + !!axisMeshInfo.max +
  72993. ')');
  72994. }
  72995. }
  72996. // Pointing Ray
  72997. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72998. if (!loadedMeshInfo.pointingPoseNode) {
  72999. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  73000. }
  73001. else {
  73002. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  73003. }
  73004. return loadedMeshInfo;
  73005. // Look through all children recursively. This will return null if no mesh exists with the given name.
  73006. function getChildByName(node, name) {
  73007. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  73008. }
  73009. // Look through only immediate children. This will return null if no mesh exists with the given name.
  73010. function getImmediateChildByName(node, name) {
  73011. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  73012. }
  73013. };
  73014. /**
  73015. * Gets the ray of the controller in the direction the controller is pointing
  73016. * @param length the length the resulting ray should be
  73017. * @returns a ray in the direction the controller is pointing
  73018. */
  73019. WindowsMotionController.prototype.getForwardRay = function (length) {
  73020. if (length === void 0) { length = 100; }
  73021. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  73022. return _super.prototype.getForwardRay.call(this, length);
  73023. }
  73024. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  73025. var origin = m.getTranslation();
  73026. var forward = new BABYLON.Vector3(0, 0, -1);
  73027. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  73028. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  73029. return new BABYLON.Ray(origin, direction, length);
  73030. };
  73031. /**
  73032. * Disposes of the controller
  73033. */
  73034. WindowsMotionController.prototype.dispose = function () {
  73035. _super.prototype.dispose.call(this);
  73036. this.onTrackpadChangedObservable.clear();
  73037. };
  73038. /**
  73039. * The base url used to load the left and right controller models
  73040. */
  73041. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  73042. /**
  73043. * The name of the left controller model file
  73044. */
  73045. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  73046. /**
  73047. * The name of the right controller model file
  73048. */
  73049. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  73050. /**
  73051. * The controller name prefix for this controller type
  73052. */
  73053. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  73054. /**
  73055. * The controller id pattern for this controller type
  73056. */
  73057. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  73058. return WindowsMotionController;
  73059. }(BABYLON.WebVRController));
  73060. BABYLON.WindowsMotionController = WindowsMotionController;
  73061. })(BABYLON || (BABYLON = {}));
  73062. //# sourceMappingURL=babylon.windowsMotionController.js.map
  73063. var BABYLON;
  73064. (function (BABYLON) {
  73065. /**
  73066. * Gear VR Controller
  73067. */
  73068. var GearVRController = /** @class */ (function (_super) {
  73069. __extends(GearVRController, _super);
  73070. /**
  73071. * Creates a new GearVRController from a gamepad
  73072. * @param vrGamepad the gamepad that the controller should be created from
  73073. */
  73074. function GearVRController(vrGamepad) {
  73075. var _this = _super.call(this, vrGamepad) || this;
  73076. _this._buttonIndexToObservableNameMap = [
  73077. 'onTrackpadChangedObservable',
  73078. 'onTriggerStateChangedObservable' // Trigger
  73079. ];
  73080. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  73081. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  73082. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  73083. return _this;
  73084. }
  73085. /**
  73086. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73087. * @param scene scene in which to add meshes
  73088. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73089. */
  73090. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73091. var _this = this;
  73092. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  73093. _this._defaultModel = newMeshes[1];
  73094. _this.attachToMesh(_this._defaultModel);
  73095. if (meshLoaded) {
  73096. meshLoaded(_this._defaultModel);
  73097. }
  73098. });
  73099. };
  73100. /**
  73101. * Called once for each button that changed state since the last frame
  73102. * @param buttonIdx Which button index changed
  73103. * @param state New state of the button
  73104. * @param changes Which properties on the state changed since last frame
  73105. */
  73106. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73107. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  73108. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  73109. // Only emit events for buttons that we know how to map from index to observable
  73110. var observable = this[observableName];
  73111. if (observable) {
  73112. observable.notifyObservers(state);
  73113. }
  73114. }
  73115. };
  73116. /**
  73117. * Base Url for the controller model.
  73118. */
  73119. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73120. /**
  73121. * File name for the controller model.
  73122. */
  73123. GearVRController.MODEL_FILENAME = 'generic.babylon';
  73124. /**
  73125. * Gamepad Id prefix used to identify this controller.
  73126. */
  73127. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  73128. return GearVRController;
  73129. }(BABYLON.WebVRController));
  73130. BABYLON.GearVRController = GearVRController;
  73131. })(BABYLON || (BABYLON = {}));
  73132. //# sourceMappingURL=babylon.gearVRController.js.map
  73133. var BABYLON;
  73134. (function (BABYLON) {
  73135. /**
  73136. * Google Daydream controller
  73137. */
  73138. var DaydreamController = /** @class */ (function (_super) {
  73139. __extends(DaydreamController, _super);
  73140. /**
  73141. * Creates a new DaydreamController from a gamepad
  73142. * @param vrGamepad the gamepad that the controller should be created from
  73143. */
  73144. function DaydreamController(vrGamepad) {
  73145. var _this = _super.call(this, vrGamepad) || this;
  73146. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  73147. return _this;
  73148. }
  73149. /**
  73150. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  73151. * @param scene scene in which to add meshes
  73152. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  73153. */
  73154. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  73155. var _this = this;
  73156. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  73157. _this._defaultModel = newMeshes[1];
  73158. _this.attachToMesh(_this._defaultModel);
  73159. if (meshLoaded) {
  73160. meshLoaded(_this._defaultModel);
  73161. }
  73162. });
  73163. };
  73164. /**
  73165. * Called once for each button that changed state since the last frame
  73166. * @param buttonIdx Which button index changed
  73167. * @param state New state of the button
  73168. * @param changes Which properties on the state changed since last frame
  73169. */
  73170. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  73171. // Daydream controller only has 1 GamepadButton (on the trackpad).
  73172. if (buttonIdx === 0) {
  73173. var observable = this.onTriggerStateChangedObservable;
  73174. if (observable) {
  73175. observable.notifyObservers(state);
  73176. }
  73177. }
  73178. else {
  73179. // If the app or home buttons are ever made available
  73180. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  73181. }
  73182. };
  73183. /**
  73184. * Base Url for the controller model.
  73185. */
  73186. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  73187. /**
  73188. * File name for the controller model.
  73189. */
  73190. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  73191. /**
  73192. * Gamepad Id prefix used to identify Daydream Controller.
  73193. */
  73194. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  73195. return DaydreamController;
  73196. }(BABYLON.WebVRController));
  73197. BABYLON.DaydreamController = DaydreamController;
  73198. })(BABYLON || (BABYLON = {}));
  73199. //# sourceMappingURL=babylon.daydreamController.js.map
  73200. var BABYLON;
  73201. (function (BABYLON) {
  73202. var FollowCamera = /** @class */ (function (_super) {
  73203. __extends(FollowCamera, _super);
  73204. function FollowCamera(name, position, scene, lockedTarget) {
  73205. if (lockedTarget === void 0) { lockedTarget = null; }
  73206. var _this = _super.call(this, name, position, scene) || this;
  73207. _this.radius = 12;
  73208. _this.rotationOffset = 0;
  73209. _this.heightOffset = 4;
  73210. _this.cameraAcceleration = 0.05;
  73211. _this.maxCameraSpeed = 20;
  73212. _this.lockedTarget = lockedTarget;
  73213. return _this;
  73214. }
  73215. FollowCamera.prototype.getRadians = function (degrees) {
  73216. return degrees * Math.PI / 180;
  73217. };
  73218. FollowCamera.prototype.follow = function (cameraTarget) {
  73219. if (!cameraTarget)
  73220. return;
  73221. var yRotation;
  73222. if (cameraTarget.rotationQuaternion) {
  73223. var rotMatrix = new BABYLON.Matrix();
  73224. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  73225. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  73226. }
  73227. else {
  73228. yRotation = cameraTarget.rotation.y;
  73229. }
  73230. var radians = this.getRadians(this.rotationOffset) + yRotation;
  73231. var targetPosition = cameraTarget.getAbsolutePosition();
  73232. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73233. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73234. var dx = targetX - this.position.x;
  73235. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73236. var dz = (targetZ) - this.position.z;
  73237. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73238. var vy = dy * this.cameraAcceleration;
  73239. var vz = dz * this.cameraAcceleration * 2;
  73240. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73241. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73242. }
  73243. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73244. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73245. }
  73246. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73247. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73248. }
  73249. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73250. this.setTarget(targetPosition);
  73251. };
  73252. FollowCamera.prototype._checkInputs = function () {
  73253. _super.prototype._checkInputs.call(this);
  73254. if (this.lockedTarget) {
  73255. this.follow(this.lockedTarget);
  73256. }
  73257. };
  73258. FollowCamera.prototype.getClassName = function () {
  73259. return "FollowCamera";
  73260. };
  73261. __decorate([
  73262. BABYLON.serialize()
  73263. ], FollowCamera.prototype, "radius", void 0);
  73264. __decorate([
  73265. BABYLON.serialize()
  73266. ], FollowCamera.prototype, "rotationOffset", void 0);
  73267. __decorate([
  73268. BABYLON.serialize()
  73269. ], FollowCamera.prototype, "heightOffset", void 0);
  73270. __decorate([
  73271. BABYLON.serialize()
  73272. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73273. __decorate([
  73274. BABYLON.serialize()
  73275. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73276. __decorate([
  73277. BABYLON.serializeAsMeshReference("lockedTargetId")
  73278. ], FollowCamera.prototype, "lockedTarget", void 0);
  73279. return FollowCamera;
  73280. }(BABYLON.TargetCamera));
  73281. BABYLON.FollowCamera = FollowCamera;
  73282. var ArcFollowCamera = /** @class */ (function (_super) {
  73283. __extends(ArcFollowCamera, _super);
  73284. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73285. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73286. _this.alpha = alpha;
  73287. _this.beta = beta;
  73288. _this.radius = radius;
  73289. _this.target = target;
  73290. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73291. _this.follow();
  73292. return _this;
  73293. }
  73294. ArcFollowCamera.prototype.follow = function () {
  73295. if (!this.target) {
  73296. return;
  73297. }
  73298. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73299. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73300. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73301. var targetPosition = this.target.getAbsolutePosition();
  73302. this.position = targetPosition.add(this._cartesianCoordinates);
  73303. this.setTarget(targetPosition);
  73304. };
  73305. ArcFollowCamera.prototype._checkInputs = function () {
  73306. _super.prototype._checkInputs.call(this);
  73307. this.follow();
  73308. };
  73309. ArcFollowCamera.prototype.getClassName = function () {
  73310. return "ArcFollowCamera";
  73311. };
  73312. return ArcFollowCamera;
  73313. }(BABYLON.TargetCamera));
  73314. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73315. })(BABYLON || (BABYLON = {}));
  73316. //# sourceMappingURL=babylon.followCamera.js.map
  73317. var BABYLON;
  73318. (function (BABYLON) {
  73319. // We're mainly based on the logic defined into the FreeCamera code
  73320. var UniversalCamera = /** @class */ (function (_super) {
  73321. __extends(UniversalCamera, _super);
  73322. //-- end properties for backward compatibility for inputs
  73323. function UniversalCamera(name, position, scene) {
  73324. var _this = _super.call(this, name, position, scene) || this;
  73325. _this.inputs.addGamepad();
  73326. return _this;
  73327. }
  73328. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73329. //-- Begin properties for backward compatibility for inputs
  73330. get: function () {
  73331. var gamepad = this.inputs.attached["gamepad"];
  73332. if (gamepad)
  73333. return gamepad.gamepadAngularSensibility;
  73334. return 0;
  73335. },
  73336. set: function (value) {
  73337. var gamepad = this.inputs.attached["gamepad"];
  73338. if (gamepad)
  73339. gamepad.gamepadAngularSensibility = value;
  73340. },
  73341. enumerable: true,
  73342. configurable: true
  73343. });
  73344. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73345. get: function () {
  73346. var gamepad = this.inputs.attached["gamepad"];
  73347. if (gamepad)
  73348. return gamepad.gamepadMoveSensibility;
  73349. return 0;
  73350. },
  73351. set: function (value) {
  73352. var gamepad = this.inputs.attached["gamepad"];
  73353. if (gamepad)
  73354. gamepad.gamepadMoveSensibility = value;
  73355. },
  73356. enumerable: true,
  73357. configurable: true
  73358. });
  73359. UniversalCamera.prototype.getClassName = function () {
  73360. return "UniversalCamera";
  73361. };
  73362. return UniversalCamera;
  73363. }(BABYLON.TouchCamera));
  73364. BABYLON.UniversalCamera = UniversalCamera;
  73365. })(BABYLON || (BABYLON = {}));
  73366. //# sourceMappingURL=babylon.universalCamera.js.map
  73367. var BABYLON;
  73368. (function (BABYLON) {
  73369. // We're mainly based on the logic defined into the FreeCamera code
  73370. var GamepadCamera = /** @class */ (function (_super) {
  73371. __extends(GamepadCamera, _super);
  73372. //-- end properties for backward compatibility for inputs
  73373. function GamepadCamera(name, position, scene) {
  73374. return _super.call(this, name, position, scene) || this;
  73375. }
  73376. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73377. //-- Begin properties for backward compatibility for inputs
  73378. get: function () {
  73379. var gamepad = this.inputs.attached["gamepad"];
  73380. if (gamepad)
  73381. return gamepad.gamepadAngularSensibility;
  73382. return 0;
  73383. },
  73384. set: function (value) {
  73385. var gamepad = this.inputs.attached["gamepad"];
  73386. if (gamepad)
  73387. gamepad.gamepadAngularSensibility = value;
  73388. },
  73389. enumerable: true,
  73390. configurable: true
  73391. });
  73392. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73393. get: function () {
  73394. var gamepad = this.inputs.attached["gamepad"];
  73395. if (gamepad)
  73396. return gamepad.gamepadMoveSensibility;
  73397. return 0;
  73398. },
  73399. set: function (value) {
  73400. var gamepad = this.inputs.attached["gamepad"];
  73401. if (gamepad)
  73402. gamepad.gamepadMoveSensibility = value;
  73403. },
  73404. enumerable: true,
  73405. configurable: true
  73406. });
  73407. GamepadCamera.prototype.getClassName = function () {
  73408. return "GamepadCamera";
  73409. };
  73410. return GamepadCamera;
  73411. }(BABYLON.UniversalCamera));
  73412. BABYLON.GamepadCamera = GamepadCamera;
  73413. })(BABYLON || (BABYLON = {}));
  73414. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73415. var BABYLON;
  73416. (function (BABYLON) {
  73417. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73418. function PostProcessRenderPipelineManager() {
  73419. this._renderPipelines = {};
  73420. }
  73421. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73422. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73423. };
  73424. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73425. if (unique === void 0) { unique = false; }
  73426. var renderPipeline = this._renderPipelines[renderPipelineName];
  73427. if (!renderPipeline) {
  73428. return;
  73429. }
  73430. renderPipeline._attachCameras(cameras, unique);
  73431. };
  73432. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73433. var renderPipeline = this._renderPipelines[renderPipelineName];
  73434. if (!renderPipeline) {
  73435. return;
  73436. }
  73437. renderPipeline._detachCameras(cameras);
  73438. };
  73439. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73440. var renderPipeline = this._renderPipelines[renderPipelineName];
  73441. if (!renderPipeline) {
  73442. return;
  73443. }
  73444. renderPipeline._enableEffect(renderEffectName, cameras);
  73445. };
  73446. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73447. var renderPipeline = this._renderPipelines[renderPipelineName];
  73448. if (!renderPipeline) {
  73449. return;
  73450. }
  73451. renderPipeline._disableEffect(renderEffectName, cameras);
  73452. };
  73453. PostProcessRenderPipelineManager.prototype.update = function () {
  73454. for (var renderPipelineName in this._renderPipelines) {
  73455. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73456. var pipeline = this._renderPipelines[renderPipelineName];
  73457. if (!pipeline.isSupported) {
  73458. pipeline.dispose();
  73459. delete this._renderPipelines[renderPipelineName];
  73460. }
  73461. else {
  73462. pipeline._update();
  73463. }
  73464. }
  73465. }
  73466. };
  73467. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73468. for (var renderPipelineName in this._renderPipelines) {
  73469. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73470. var pipeline = this._renderPipelines[renderPipelineName];
  73471. pipeline._rebuild();
  73472. }
  73473. }
  73474. };
  73475. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73476. for (var renderPipelineName in this._renderPipelines) {
  73477. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73478. var pipeline = this._renderPipelines[renderPipelineName];
  73479. pipeline.dispose();
  73480. }
  73481. }
  73482. };
  73483. return PostProcessRenderPipelineManager;
  73484. }());
  73485. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73486. })(BABYLON || (BABYLON = {}));
  73487. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73488. var BABYLON;
  73489. (function (BABYLON) {
  73490. /**
  73491. * This represents a set of one or more post processes in Babylon.
  73492. * A post process can be used to apply a shader to a texture after it is rendered.
  73493. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73494. */
  73495. var PostProcessRenderEffect = /** @class */ (function () {
  73496. /**
  73497. * Instantiates a post process render effect.
  73498. * A post process can be used to apply a shader to a texture after it is rendered.
  73499. * @param engine The engine the effect is tied to
  73500. * @param name The name of the effect
  73501. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73502. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73503. */
  73504. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73505. this._name = name;
  73506. this._singleInstance = singleInstance || true;
  73507. this._getPostProcesses = getPostProcesses;
  73508. this._cameras = {};
  73509. this._indicesForCamera = {};
  73510. this._postProcesses = {};
  73511. }
  73512. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73513. /**
  73514. * Checks if all the post processes in the effect are supported.
  73515. */
  73516. get: function () {
  73517. for (var index in this._postProcesses) {
  73518. if (this._postProcesses.hasOwnProperty(index)) {
  73519. var pps = this._postProcesses[index];
  73520. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73521. if (!pps[ppIndex].isSupported) {
  73522. return false;
  73523. }
  73524. }
  73525. }
  73526. }
  73527. return true;
  73528. },
  73529. enumerable: true,
  73530. configurable: true
  73531. });
  73532. /**
  73533. * Updates the current state of the effect
  73534. */
  73535. PostProcessRenderEffect.prototype._update = function () {
  73536. };
  73537. /**
  73538. * Attaches the effect on cameras
  73539. * @param cameras The camera to attach to.
  73540. */
  73541. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73542. var _this = this;
  73543. var cameraKey;
  73544. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73545. if (!cams) {
  73546. return;
  73547. }
  73548. for (var i = 0; i < cams.length; i++) {
  73549. var camera = cams[i];
  73550. var cameraName = camera.name;
  73551. if (this._singleInstance) {
  73552. cameraKey = 0;
  73553. }
  73554. else {
  73555. cameraKey = cameraName;
  73556. }
  73557. if (!this._postProcesses[cameraKey]) {
  73558. var postProcess = this._getPostProcesses();
  73559. if (postProcess) {
  73560. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73561. }
  73562. }
  73563. if (!this._indicesForCamera[cameraName]) {
  73564. this._indicesForCamera[cameraName] = [];
  73565. }
  73566. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73567. var index = camera.attachPostProcess(postProcess);
  73568. _this._indicesForCamera[cameraName].push(index);
  73569. });
  73570. if (!this._cameras[cameraName]) {
  73571. this._cameras[cameraName] = camera;
  73572. }
  73573. }
  73574. };
  73575. /**
  73576. * Detatches the effect on cameras
  73577. * @param cameras The camera to detatch from.
  73578. */
  73579. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73580. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73581. if (!cams) {
  73582. return;
  73583. }
  73584. for (var i = 0; i < cams.length; i++) {
  73585. var camera = cams[i];
  73586. var cameraName = camera.name;
  73587. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73588. camera.detachPostProcess(postProcess);
  73589. });
  73590. if (this._cameras[cameraName]) {
  73591. //this._indicesForCamera.splice(index, 1);
  73592. this._cameras[cameraName] = null;
  73593. }
  73594. }
  73595. };
  73596. /**
  73597. * Enables the effect on given cameras
  73598. * @param cameras The camera to enable.
  73599. */
  73600. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73601. var _this = this;
  73602. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73603. if (!cams) {
  73604. return;
  73605. }
  73606. for (var i = 0; i < cams.length; i++) {
  73607. var camera = cams[i];
  73608. var cameraName = camera.name;
  73609. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73610. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73611. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73612. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73613. });
  73614. }
  73615. }
  73616. }
  73617. };
  73618. /**
  73619. * Disables the effect on the given cameras
  73620. * @param cameras The camera to disable.
  73621. */
  73622. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73623. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73624. if (!cams) {
  73625. return;
  73626. }
  73627. for (var i = 0; i < cams.length; i++) {
  73628. var camera = cams[i];
  73629. var cameraName = camera.name;
  73630. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73631. camera.detachPostProcess(postProcess);
  73632. });
  73633. }
  73634. };
  73635. /**
  73636. * Gets a list of the post processes contained in the effect.
  73637. * @param camera The camera to get the post processes on.
  73638. * @returns The list of the post processes in the effect.
  73639. */
  73640. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73641. if (this._singleInstance) {
  73642. return this._postProcesses[0];
  73643. }
  73644. else {
  73645. if (!camera) {
  73646. return null;
  73647. }
  73648. return this._postProcesses[camera.name];
  73649. }
  73650. };
  73651. return PostProcessRenderEffect;
  73652. }());
  73653. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73654. })(BABYLON || (BABYLON = {}));
  73655. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73656. var BABYLON;
  73657. (function (BABYLON) {
  73658. var PostProcessRenderPipeline = /** @class */ (function () {
  73659. function PostProcessRenderPipeline(engine, name) {
  73660. this.engine = engine;
  73661. this._name = name;
  73662. this._renderEffects = {};
  73663. this._renderEffectsForIsolatedPass = new Array();
  73664. this._cameras = [];
  73665. }
  73666. PostProcessRenderPipeline.prototype.getClassName = function () {
  73667. return "PostProcessRenderPipeline";
  73668. };
  73669. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73670. get: function () {
  73671. for (var renderEffectName in this._renderEffects) {
  73672. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73673. if (!this._renderEffects[renderEffectName].isSupported) {
  73674. return false;
  73675. }
  73676. }
  73677. }
  73678. return true;
  73679. },
  73680. enumerable: true,
  73681. configurable: true
  73682. });
  73683. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73684. this._renderEffects[renderEffect._name] = renderEffect;
  73685. };
  73686. // private
  73687. PostProcessRenderPipeline.prototype._rebuild = function () {
  73688. };
  73689. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73690. var renderEffects = this._renderEffects[renderEffectName];
  73691. if (!renderEffects) {
  73692. return;
  73693. }
  73694. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73695. };
  73696. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73697. var renderEffects = this._renderEffects[renderEffectName];
  73698. if (!renderEffects) {
  73699. return;
  73700. }
  73701. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73702. };
  73703. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73704. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73705. if (!cams) {
  73706. return;
  73707. }
  73708. var indicesToDelete = [];
  73709. var i;
  73710. for (i = 0; i < cams.length; i++) {
  73711. var camera = cams[i];
  73712. var cameraName = camera.name;
  73713. if (this._cameras.indexOf(camera) === -1) {
  73714. this._cameras[cameraName] = camera;
  73715. }
  73716. else if (unique) {
  73717. indicesToDelete.push(i);
  73718. }
  73719. }
  73720. for (i = 0; i < indicesToDelete.length; i++) {
  73721. cameras.splice(indicesToDelete[i], 1);
  73722. }
  73723. for (var renderEffectName in this._renderEffects) {
  73724. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73725. this._renderEffects[renderEffectName]._attachCameras(cams);
  73726. }
  73727. }
  73728. };
  73729. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73730. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73731. if (!cams) {
  73732. return;
  73733. }
  73734. for (var renderEffectName in this._renderEffects) {
  73735. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73736. this._renderEffects[renderEffectName]._detachCameras(cams);
  73737. }
  73738. }
  73739. for (var i = 0; i < cams.length; i++) {
  73740. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73741. }
  73742. };
  73743. PostProcessRenderPipeline.prototype._update = function () {
  73744. for (var renderEffectName in this._renderEffects) {
  73745. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73746. this._renderEffects[renderEffectName]._update();
  73747. }
  73748. }
  73749. for (var i = 0; i < this._cameras.length; i++) {
  73750. var cameraName = this._cameras[i].name;
  73751. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73752. this._renderEffectsForIsolatedPass[cameraName]._update();
  73753. }
  73754. }
  73755. };
  73756. PostProcessRenderPipeline.prototype._reset = function () {
  73757. this._renderEffects = {};
  73758. this._renderEffectsForIsolatedPass = new Array();
  73759. };
  73760. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73761. // 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)
  73762. var effectKeys = Object.keys(this._renderEffects);
  73763. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73764. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73765. if (postProcesses) {
  73766. postProcesses[0].samples = sampleCount;
  73767. return true;
  73768. }
  73769. }
  73770. return false;
  73771. };
  73772. PostProcessRenderPipeline.prototype.dispose = function () {
  73773. // Must be implemented by children
  73774. };
  73775. __decorate([
  73776. BABYLON.serialize()
  73777. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73778. return PostProcessRenderPipeline;
  73779. }());
  73780. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73781. })(BABYLON || (BABYLON = {}));
  73782. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73783. var BABYLON;
  73784. (function (BABYLON) {
  73785. /**
  73786. * This represents a depth renderer in Babylon.
  73787. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73788. */
  73789. var DepthRenderer = /** @class */ (function () {
  73790. /**
  73791. * Instantiates a depth renderer
  73792. * @param scene The scene the renderer belongs to
  73793. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73794. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73795. */
  73796. function DepthRenderer(scene, type, camera) {
  73797. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73798. if (camera === void 0) { camera = null; }
  73799. var _this = this;
  73800. this._scene = scene;
  73801. this._camera = camera;
  73802. var engine = scene.getEngine();
  73803. // Render target
  73804. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73805. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73806. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73807. this._depthMap.refreshRate = 1;
  73808. this._depthMap.renderParticles = false;
  73809. this._depthMap.renderList = null;
  73810. // Camera to get depth map from to support multiple concurrent cameras
  73811. this._depthMap.activeCamera = this._camera;
  73812. this._depthMap.ignoreCameraViewport = true;
  73813. this._depthMap.useCameraPostProcesses = false;
  73814. // set default depth value to 1.0 (far away)
  73815. this._depthMap.onClearObservable.add(function (engine) {
  73816. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73817. });
  73818. // Custom render function
  73819. var renderSubMesh = function (subMesh) {
  73820. var mesh = subMesh.getRenderingMesh();
  73821. var scene = _this._scene;
  73822. var engine = scene.getEngine();
  73823. var material = subMesh.getMaterial();
  73824. if (!material) {
  73825. return;
  73826. }
  73827. // Culling and reverse (right handed system)
  73828. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73829. // Managing instances
  73830. var batch = mesh._getInstancesRenderList(subMesh._id);
  73831. if (batch.mustReturn) {
  73832. return;
  73833. }
  73834. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73835. var camera = _this._camera || scene.activeCamera;
  73836. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73837. engine.enableEffect(_this._effect);
  73838. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73839. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73840. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73841. // Alpha test
  73842. if (material && material.needAlphaTesting()) {
  73843. var alphaTexture = material.getAlphaTestTexture();
  73844. if (alphaTexture) {
  73845. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73846. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73847. }
  73848. }
  73849. // Bones
  73850. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73851. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73852. }
  73853. // Draw
  73854. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73855. }
  73856. };
  73857. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73858. var index;
  73859. if (depthOnlySubMeshes.length) {
  73860. engine.setColorWrite(false);
  73861. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73862. renderSubMesh(depthOnlySubMeshes.data[index]);
  73863. }
  73864. engine.setColorWrite(true);
  73865. }
  73866. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73867. renderSubMesh(opaqueSubMeshes.data[index]);
  73868. }
  73869. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73870. renderSubMesh(alphaTestSubMeshes.data[index]);
  73871. }
  73872. };
  73873. }
  73874. /**
  73875. * Creates the depth rendering effect and checks if the effect is ready.
  73876. * @param subMesh The submesh to be used to render the depth map of
  73877. * @param useInstances If multiple world instances should be used
  73878. * @returns if the depth renderer is ready to render the depth map
  73879. */
  73880. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73881. var material = subMesh.getMaterial();
  73882. if (material.disableDepthWrite) {
  73883. return false;
  73884. }
  73885. var defines = [];
  73886. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73887. var mesh = subMesh.getMesh();
  73888. // Alpha test
  73889. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73890. defines.push("#define ALPHATEST");
  73891. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73892. attribs.push(BABYLON.VertexBuffer.UVKind);
  73893. defines.push("#define UV1");
  73894. }
  73895. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73896. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73897. defines.push("#define UV2");
  73898. }
  73899. }
  73900. // Bones
  73901. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73904. if (mesh.numBoneInfluencers > 4) {
  73905. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73906. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73907. }
  73908. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73909. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73910. }
  73911. else {
  73912. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73913. }
  73914. // Instances
  73915. if (useInstances) {
  73916. defines.push("#define INSTANCES");
  73917. attribs.push("world0");
  73918. attribs.push("world1");
  73919. attribs.push("world2");
  73920. attribs.push("world3");
  73921. }
  73922. // Get correct effect
  73923. var join = defines.join("\n");
  73924. if (this._cachedDefines !== join) {
  73925. this._cachedDefines = join;
  73926. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73927. }
  73928. return this._effect.isReady();
  73929. };
  73930. /**
  73931. * Gets the texture which the depth map will be written to.
  73932. * @returns The depth map texture
  73933. */
  73934. DepthRenderer.prototype.getDepthMap = function () {
  73935. return this._depthMap;
  73936. };
  73937. /**
  73938. * Disposes of the depth renderer.
  73939. */
  73940. DepthRenderer.prototype.dispose = function () {
  73941. this._depthMap.dispose();
  73942. };
  73943. return DepthRenderer;
  73944. }());
  73945. BABYLON.DepthRenderer = DepthRenderer;
  73946. })(BABYLON || (BABYLON = {}));
  73947. //# sourceMappingURL=babylon.depthRenderer.js.map
  73948. var BABYLON;
  73949. (function (BABYLON) {
  73950. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73951. __extends(SSAORenderingPipeline, _super);
  73952. /**
  73953. * @constructor
  73954. * @param {string} name - The rendering pipeline name
  73955. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73956. * @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 }
  73957. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73958. */
  73959. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73960. var _this = _super.call(this, scene.getEngine(), name) || this;
  73961. // Members
  73962. /**
  73963. * The PassPostProcess id in the pipeline that contains the original scene color
  73964. */
  73965. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73966. /**
  73967. * The SSAO PostProcess id in the pipeline
  73968. */
  73969. _this.SSAORenderEffect = "SSAORenderEffect";
  73970. /**
  73971. * The horizontal blur PostProcess id in the pipeline
  73972. */
  73973. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73974. /**
  73975. * The vertical blur PostProcess id in the pipeline
  73976. */
  73977. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73978. /**
  73979. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73980. */
  73981. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73982. /**
  73983. * The output strength of the SSAO post-process. Default value is 1.0.
  73984. */
  73985. _this.totalStrength = 1.0;
  73986. /**
  73987. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73988. */
  73989. _this.radius = 0.0001;
  73990. /**
  73991. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73992. * Must not be equal to fallOff and superior to fallOff.
  73993. * Default value is 0.975
  73994. */
  73995. _this.area = 0.0075;
  73996. /**
  73997. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73998. * Must not be equal to area and inferior to area.
  73999. * Default value is 0.0
  74000. */
  74001. _this.fallOff = 0.000001;
  74002. /**
  74003. * The base color of the SSAO post-process
  74004. * The final result is "base + ssao" between [0, 1]
  74005. */
  74006. _this.base = 0.5;
  74007. _this._firstUpdate = true;
  74008. _this._scene = scene;
  74009. // Set up assets
  74010. _this._createRandomTexture();
  74011. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74012. var ssaoRatio = ratio.ssaoRatio || ratio;
  74013. var combineRatio = ratio.combineRatio || ratio;
  74014. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74015. _this._createSSAOPostProcess(ssaoRatio);
  74016. _this._createBlurPostProcess(ssaoRatio);
  74017. _this._createSSAOCombinePostProcess(combineRatio);
  74018. // Set up pipeline
  74019. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74023. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74024. // Finish
  74025. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74026. if (cameras)
  74027. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74028. return _this;
  74029. }
  74030. // Public Methods
  74031. /**
  74032. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74033. */
  74034. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74035. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74036. for (var i = 0; i < this._scene.cameras.length; i++) {
  74037. var camera = this._scene.cameras[i];
  74038. this._originalColorPostProcess.dispose(camera);
  74039. this._ssaoPostProcess.dispose(camera);
  74040. this._blurHPostProcess.dispose(camera);
  74041. this._blurVPostProcess.dispose(camera);
  74042. this._ssaoCombinePostProcess.dispose(camera);
  74043. }
  74044. this._randomTexture.dispose();
  74045. if (disableDepthRender)
  74046. this._scene.disableDepthRenderer();
  74047. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74048. _super.prototype.dispose.call(this);
  74049. };
  74050. // Private Methods
  74051. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  74052. var _this = this;
  74053. var size = 16;
  74054. 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);
  74055. 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);
  74056. this._blurHPostProcess.onActivateObservable.add(function () {
  74057. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  74058. _this._blurHPostProcess.kernel = size * dw;
  74059. });
  74060. this._blurVPostProcess.onActivateObservable.add(function () {
  74061. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  74062. _this._blurVPostProcess.kernel = size * dw;
  74063. });
  74064. };
  74065. SSAORenderingPipeline.prototype._rebuild = function () {
  74066. this._firstUpdate = true;
  74067. _super.prototype._rebuild.call(this);
  74068. };
  74069. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74070. var _this = this;
  74071. var numSamples = 16;
  74072. var sampleSphere = [
  74073. 0.5381, 0.1856, -0.4319,
  74074. 0.1379, 0.2486, 0.4430,
  74075. 0.3371, 0.5679, -0.0057,
  74076. -0.6999, -0.0451, -0.0019,
  74077. 0.0689, -0.1598, -0.8547,
  74078. 0.0560, 0.0069, -0.1843,
  74079. -0.0146, 0.1402, 0.0762,
  74080. 0.0100, -0.1924, -0.0344,
  74081. -0.3577, -0.5301, -0.4358,
  74082. -0.3169, 0.1063, 0.0158,
  74083. 0.0103, -0.5869, 0.0046,
  74084. -0.0897, -0.4940, 0.3287,
  74085. 0.7119, -0.0154, -0.0918,
  74086. -0.0533, 0.0596, -0.5411,
  74087. 0.0352, -0.0631, 0.5460,
  74088. -0.4776, 0.2847, -0.0271
  74089. ];
  74090. var samplesFactor = 1.0 / numSamples;
  74091. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  74092. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74093. "area", "fallOff", "base", "range", "viewport"
  74094. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74095. this._ssaoPostProcess.onApply = function (effect) {
  74096. if (_this._firstUpdate) {
  74097. effect.setArray3("sampleSphere", sampleSphere);
  74098. effect.setFloat("samplesFactor", samplesFactor);
  74099. effect.setFloat("randTextureTiles", 4.0);
  74100. }
  74101. effect.setFloat("totalStrength", _this.totalStrength);
  74102. effect.setFloat("radius", _this.radius);
  74103. effect.setFloat("area", _this.area);
  74104. effect.setFloat("fallOff", _this.fallOff);
  74105. effect.setFloat("base", _this.base);
  74106. effect.setTexture("textureSampler", _this._depthTexture);
  74107. effect.setTexture("randomSampler", _this._randomTexture);
  74108. };
  74109. };
  74110. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74111. var _this = this;
  74112. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74113. this._ssaoCombinePostProcess.onApply = function (effect) {
  74114. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  74115. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74116. };
  74117. };
  74118. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  74119. var size = 512;
  74120. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74121. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74122. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74123. var context = this._randomTexture.getContext();
  74124. var rand = function (min, max) {
  74125. return Math.random() * (max - min) + min;
  74126. };
  74127. var randVector = BABYLON.Vector3.Zero();
  74128. for (var x = 0; x < size; x++) {
  74129. for (var y = 0; y < size; y++) {
  74130. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  74131. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  74132. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  74133. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74134. context.fillRect(x, y, 1, 1);
  74135. }
  74136. }
  74137. this._randomTexture.update(false);
  74138. };
  74139. __decorate([
  74140. BABYLON.serialize()
  74141. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  74142. __decorate([
  74143. BABYLON.serialize()
  74144. ], SSAORenderingPipeline.prototype, "radius", void 0);
  74145. __decorate([
  74146. BABYLON.serialize()
  74147. ], SSAORenderingPipeline.prototype, "area", void 0);
  74148. __decorate([
  74149. BABYLON.serialize()
  74150. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  74151. __decorate([
  74152. BABYLON.serialize()
  74153. ], SSAORenderingPipeline.prototype, "base", void 0);
  74154. return SSAORenderingPipeline;
  74155. }(BABYLON.PostProcessRenderPipeline));
  74156. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  74157. })(BABYLON || (BABYLON = {}));
  74158. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  74159. var BABYLON;
  74160. (function (BABYLON) {
  74161. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  74162. __extends(SSAO2RenderingPipeline, _super);
  74163. /**
  74164. * @constructor
  74165. * @param {string} name - The rendering pipeline name
  74166. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74167. * @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 }
  74168. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74169. */
  74170. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  74171. var _this = _super.call(this, scene.getEngine(), name) || this;
  74172. // Members
  74173. /**
  74174. * The PassPostProcess id in the pipeline that contains the original scene color
  74175. */
  74176. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  74177. /**
  74178. * The SSAO PostProcess id in the pipeline
  74179. */
  74180. _this.SSAORenderEffect = "SSAORenderEffect";
  74181. /**
  74182. * The horizontal blur PostProcess id in the pipeline
  74183. */
  74184. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  74185. /**
  74186. * The vertical blur PostProcess id in the pipeline
  74187. */
  74188. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  74189. /**
  74190. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  74191. */
  74192. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  74193. /**
  74194. * The output strength of the SSAO post-process. Default value is 1.0.
  74195. */
  74196. _this.totalStrength = 1.0;
  74197. /**
  74198. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  74199. */
  74200. _this.maxZ = 100.0;
  74201. /**
  74202. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  74203. */
  74204. _this.minZAspect = 0.2;
  74205. /**
  74206. * Number of samples used for the SSAO calculations. Default value is 8
  74207. */
  74208. _this._samples = 8;
  74209. /**
  74210. * Are we using bilateral blur ?
  74211. */
  74212. _this._expensiveBlur = true;
  74213. /**
  74214. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  74215. */
  74216. _this.radius = 2.0;
  74217. /**
  74218. * The base color of the SSAO post-process
  74219. * The final result is "base + ssao" between [0, 1]
  74220. */
  74221. _this.base = 0.1;
  74222. _this._firstUpdate = true;
  74223. _this._scene = scene;
  74224. _this._ratio = ratio;
  74225. if (!_this.isSupported) {
  74226. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  74227. return _this;
  74228. }
  74229. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  74230. var blurRatio = _this._ratio.blurRatio || ratio;
  74231. // Set up assets
  74232. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74233. _this._createRandomTexture();
  74234. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74235. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74236. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74237. _this._createSSAOPostProcess(1.0);
  74238. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74239. _this._createSSAOCombinePostProcess(blurRatio);
  74240. // Set up pipeline
  74241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74243. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74244. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74245. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74246. // Finish
  74247. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74248. if (cameras)
  74249. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74250. return _this;
  74251. }
  74252. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74253. get: function () {
  74254. return this._samples;
  74255. },
  74256. set: function (n) {
  74257. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74258. this._samples = n;
  74259. this._sampleSphere = this._generateHemisphere();
  74260. this._firstUpdate = true;
  74261. },
  74262. enumerable: true,
  74263. configurable: true
  74264. });
  74265. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74266. get: function () {
  74267. return this._expensiveBlur;
  74268. },
  74269. set: function (b) {
  74270. 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"]);
  74271. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74272. this._expensiveBlur = b;
  74273. this._firstUpdate = true;
  74274. },
  74275. enumerable: true,
  74276. configurable: true
  74277. });
  74278. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74279. /**
  74280. * Support test.
  74281. */
  74282. get: function () {
  74283. var engine = BABYLON.Engine.LastCreatedEngine;
  74284. if (!engine) {
  74285. return false;
  74286. }
  74287. return engine.getCaps().drawBuffersExtension;
  74288. },
  74289. enumerable: true,
  74290. configurable: true
  74291. });
  74292. // Public Methods
  74293. /**
  74294. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74295. */
  74296. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74297. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74298. for (var i = 0; i < this._scene.cameras.length; i++) {
  74299. var camera = this._scene.cameras[i];
  74300. this._originalColorPostProcess.dispose(camera);
  74301. this._ssaoPostProcess.dispose(camera);
  74302. this._blurHPostProcess.dispose(camera);
  74303. this._blurVPostProcess.dispose(camera);
  74304. this._ssaoCombinePostProcess.dispose(camera);
  74305. }
  74306. this._randomTexture.dispose();
  74307. if (disableGeometryBufferRenderer)
  74308. this._scene.disableGeometryBufferRenderer();
  74309. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74310. _super.prototype.dispose.call(this);
  74311. };
  74312. // Private Methods
  74313. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74314. var _this = this;
  74315. this._samplerOffsets = [];
  74316. var expensive = this.expensiveBlur;
  74317. for (var i = -8; i < 8; i++) {
  74318. this._samplerOffsets.push(i * 2 + 0.5);
  74319. }
  74320. 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");
  74321. this._blurHPostProcess.onApply = function (effect) {
  74322. if (!_this._scene.activeCamera) {
  74323. return;
  74324. }
  74325. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74326. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74327. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74328. effect.setFloat("radius", _this.radius);
  74329. effect.setTexture("depthSampler", _this._depthTexture);
  74330. if (_this._firstUpdate) {
  74331. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74332. }
  74333. };
  74334. 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");
  74335. this._blurVPostProcess.onApply = function (effect) {
  74336. if (!_this._scene.activeCamera) {
  74337. return;
  74338. }
  74339. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74340. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74341. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74342. effect.setFloat("radius", _this.radius);
  74343. effect.setTexture("depthSampler", _this._depthTexture);
  74344. if (_this._firstUpdate) {
  74345. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74346. _this._firstUpdate = false;
  74347. }
  74348. };
  74349. };
  74350. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74351. this._firstUpdate = true;
  74352. _super.prototype._rebuild.call(this);
  74353. };
  74354. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74355. var numSamples = this.samples;
  74356. var result = [];
  74357. var vector, scale;
  74358. var rand = function (min, max) {
  74359. return Math.random() * (max - min) + min;
  74360. };
  74361. var i = 0;
  74362. while (i < numSamples) {
  74363. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74364. vector.normalize();
  74365. scale = i / numSamples;
  74366. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74367. vector.scaleInPlace(scale);
  74368. result.push(vector.x, vector.y, vector.z);
  74369. i++;
  74370. }
  74371. return result;
  74372. };
  74373. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74374. var _this = this;
  74375. var numSamples = this.samples;
  74376. this._sampleSphere = this._generateHemisphere();
  74377. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74378. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74379. "base", "range", "projection", "near", "far", "texelSize",
  74380. "xViewport", "yViewport", "maxZ", "minZAspect"
  74381. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74382. this._ssaoPostProcess.onApply = function (effect) {
  74383. if (_this._firstUpdate) {
  74384. effect.setArray3("sampleSphere", _this._sampleSphere);
  74385. effect.setFloat("randTextureTiles", 4.0);
  74386. }
  74387. if (!_this._scene.activeCamera) {
  74388. return;
  74389. }
  74390. effect.setFloat("samplesFactor", 1 / _this.samples);
  74391. effect.setFloat("totalStrength", _this.totalStrength);
  74392. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74393. effect.setFloat("radius", _this.radius);
  74394. effect.setFloat("maxZ", _this.maxZ);
  74395. effect.setFloat("minZAspect", _this.minZAspect);
  74396. effect.setFloat("base", _this.base);
  74397. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74398. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74399. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74400. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74401. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74402. effect.setTexture("textureSampler", _this._depthTexture);
  74403. effect.setTexture("normalSampler", _this._normalTexture);
  74404. effect.setTexture("randomSampler", _this._randomTexture);
  74405. };
  74406. };
  74407. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74408. var _this = this;
  74409. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74410. this._ssaoCombinePostProcess.onApply = function (effect) {
  74411. var viewport = _this._scene.activeCamera.viewport;
  74412. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74413. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74414. };
  74415. };
  74416. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74417. var size = 512;
  74418. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74419. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74420. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74421. var context = this._randomTexture.getContext();
  74422. var rand = function (min, max) {
  74423. return Math.random() * (max - min) + min;
  74424. };
  74425. var randVector = BABYLON.Vector3.Zero();
  74426. for (var x = 0; x < size; x++) {
  74427. for (var y = 0; y < size; y++) {
  74428. randVector.x = rand(0.0, 1.0);
  74429. randVector.y = rand(0.0, 1.0);
  74430. randVector.z = 0.0;
  74431. randVector.normalize();
  74432. randVector.scaleInPlace(255);
  74433. randVector.x = Math.floor(randVector.x);
  74434. randVector.y = Math.floor(randVector.y);
  74435. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74436. context.fillRect(x, y, 1, 1);
  74437. }
  74438. }
  74439. this._randomTexture.update(false);
  74440. };
  74441. /**
  74442. * Serialize the rendering pipeline (Used when exporting)
  74443. * @returns the serialized object
  74444. */
  74445. SSAO2RenderingPipeline.prototype.serialize = function () {
  74446. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74447. serializationObject.customType = "SSAO2RenderingPipeline";
  74448. return serializationObject;
  74449. };
  74450. /**
  74451. * Parse the serialized pipeline
  74452. * @param source Source pipeline.
  74453. * @param scene The scene to load the pipeline to.
  74454. * @param rootUrl The URL of the serialized pipeline.
  74455. * @returns An instantiated pipeline from the serialized object.
  74456. */
  74457. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74458. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74459. };
  74460. __decorate([
  74461. BABYLON.serialize()
  74462. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74463. __decorate([
  74464. BABYLON.serialize()
  74465. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74466. __decorate([
  74467. BABYLON.serialize()
  74468. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74469. __decorate([
  74470. BABYLON.serialize("samples")
  74471. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74472. __decorate([
  74473. BABYLON.serialize()
  74474. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74475. __decorate([
  74476. BABYLON.serialize("expensiveBlur")
  74477. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74478. __decorate([
  74479. BABYLON.serialize()
  74480. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74481. __decorate([
  74482. BABYLON.serialize()
  74483. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74484. return SSAO2RenderingPipeline;
  74485. }(BABYLON.PostProcessRenderPipeline));
  74486. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74487. })(BABYLON || (BABYLON = {}));
  74488. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74489. // BABYLON.JS Chromatic Aberration GLSL Shader
  74490. // Author: Olivier Guyot
  74491. // Separates very slightly R, G and B colors on the edges of the screen
  74492. // Inspired by Francois Tarlier & Martins Upitis
  74493. var BABYLON;
  74494. (function (BABYLON) {
  74495. var LensRenderingPipeline = /** @class */ (function (_super) {
  74496. __extends(LensRenderingPipeline, _super);
  74497. /**
  74498. * @constructor
  74499. *
  74500. * Effect parameters are as follow:
  74501. * {
  74502. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74503. * edge_blur: number; // from 0 to x (1 for realism)
  74504. * distortion: number; // from 0 to x (1 for realism)
  74505. * grain_amount: number; // from 0 to 1
  74506. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74507. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74508. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74509. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74510. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74511. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74512. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74513. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74514. * }
  74515. * Note: if an effect parameter is unset, effect is disabled
  74516. *
  74517. * @param {string} name - The rendering pipeline name
  74518. * @param {object} parameters - An object containing all parameters (see above)
  74519. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74520. * @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)
  74521. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74522. */
  74523. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74524. if (ratio === void 0) { ratio = 1.0; }
  74525. var _this = _super.call(this, scene.getEngine(), name) || this;
  74526. // Lens effects can be of the following:
  74527. // - chromatic aberration (slight shift of RGB colors)
  74528. // - blur on the edge of the lens
  74529. // - lens distortion
  74530. // - depth-of-field blur & highlights enhancing
  74531. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74532. // - grain effect (noise or custom texture)
  74533. // Two additional texture samplers are needed:
  74534. // - depth map (for depth-of-field)
  74535. // - grain texture
  74536. /**
  74537. * The chromatic aberration PostProcess id in the pipeline
  74538. */
  74539. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74540. /**
  74541. * The highlights enhancing PostProcess id in the pipeline
  74542. */
  74543. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74544. /**
  74545. * The depth-of-field PostProcess id in the pipeline
  74546. */
  74547. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74548. _this._scene = scene;
  74549. // Fetch texture samplers
  74550. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74551. if (parameters.grain_texture) {
  74552. _this._grainTexture = parameters.grain_texture;
  74553. }
  74554. else {
  74555. _this._createGrainTexture();
  74556. }
  74557. // save parameters
  74558. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74559. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74560. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74561. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74562. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74563. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74564. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74565. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74566. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74567. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74568. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74569. // Create effects
  74570. _this._createChromaticAberrationPostProcess(ratio);
  74571. _this._createHighlightsPostProcess(ratio);
  74572. _this._createDepthOfFieldPostProcess(ratio / 4);
  74573. // Set up pipeline
  74574. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74575. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74576. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74577. if (_this._highlightsGain === -1) {
  74578. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74579. }
  74580. // Finish
  74581. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74582. if (cameras) {
  74583. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74584. }
  74585. return _this;
  74586. }
  74587. // public methods (self explanatory)
  74588. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74589. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74590. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74591. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74592. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74593. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74594. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74595. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74596. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74597. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74598. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74599. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74600. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74601. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74602. };
  74603. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74604. this._highlightsPostProcess.updateEffect();
  74605. };
  74606. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74607. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74608. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74609. this._highlightsGain = amount;
  74610. };
  74611. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74612. if (this._highlightsGain === -1) {
  74613. this._highlightsGain = 1.0;
  74614. }
  74615. this._highlightsThreshold = amount;
  74616. };
  74617. LensRenderingPipeline.prototype.disableHighlights = function () {
  74618. this._highlightsGain = -1;
  74619. };
  74620. /**
  74621. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74622. */
  74623. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74624. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74625. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74626. this._chromaticAberrationPostProcess = null;
  74627. this._highlightsPostProcess = null;
  74628. this._depthOfFieldPostProcess = null;
  74629. this._grainTexture.dispose();
  74630. if (disableDepthRender)
  74631. this._scene.disableDepthRenderer();
  74632. };
  74633. // colors shifting and distortion
  74634. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74635. var _this = this;
  74636. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74637. [], // samplers
  74638. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74639. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74640. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74641. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74642. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74643. effect.setFloat('radialIntensity', 1);
  74644. effect.setFloat2('direction', 17, 17);
  74645. effect.setFloat2('centerPosition', 0.5, 0.5);
  74646. };
  74647. };
  74648. // highlights enhancing
  74649. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74650. var _this = this;
  74651. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74652. [], // samplers
  74653. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74654. this._highlightsPostProcess.onApply = function (effect) {
  74655. effect.setFloat('gain', _this._highlightsGain);
  74656. effect.setFloat('threshold', _this._highlightsThreshold);
  74657. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74658. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74659. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74660. };
  74661. };
  74662. // colors shifting and distortion
  74663. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74664. var _this = this;
  74665. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74666. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74667. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74668. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74669. this._depthOfFieldPostProcess.onApply = function (effect) {
  74670. effect.setTexture("depthSampler", _this._depthTexture);
  74671. effect.setTexture("grainSampler", _this._grainTexture);
  74672. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74673. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74674. effect.setFloat('grain_amount', _this._grainAmount);
  74675. effect.setBool('blur_noise', _this._blurNoise);
  74676. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74677. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74678. effect.setFloat('distortion', _this._distortion);
  74679. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74680. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74681. effect.setFloat('aperture', _this._dofAperture);
  74682. effect.setFloat('darken', _this._dofDarken);
  74683. effect.setFloat('edge_blur', _this._edgeBlur);
  74684. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74685. if (_this._scene.activeCamera) {
  74686. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74687. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74688. }
  74689. };
  74690. };
  74691. // creates a black and white random noise texture, 512x512
  74692. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74693. var size = 512;
  74694. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74695. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74696. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74697. var context = this._grainTexture.getContext();
  74698. var rand = function (min, max) {
  74699. return Math.random() * (max - min) + min;
  74700. };
  74701. var value;
  74702. for (var x = 0; x < size; x++) {
  74703. for (var y = 0; y < size; y++) {
  74704. value = Math.floor(rand(0.42, 0.58) * 255);
  74705. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74706. context.fillRect(x, y, 1, 1);
  74707. }
  74708. }
  74709. this._grainTexture.update(false);
  74710. };
  74711. return LensRenderingPipeline;
  74712. }(BABYLON.PostProcessRenderPipeline));
  74713. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74714. })(BABYLON || (BABYLON = {}));
  74715. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74716. var BABYLON;
  74717. (function (BABYLON) {
  74718. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74719. __extends(StandardRenderingPipeline, _super);
  74720. /**
  74721. * @constructor
  74722. * @param {string} name - The rendering pipeline name
  74723. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74724. * @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)
  74725. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74726. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74727. */
  74728. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74729. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74730. var _this = _super.call(this, scene.getEngine(), name) || this;
  74731. _this.downSampleX4PostProcess = null;
  74732. _this.brightPassPostProcess = null;
  74733. _this.blurHPostProcesses = [];
  74734. _this.blurVPostProcesses = [];
  74735. _this.textureAdderPostProcess = null;
  74736. _this.volumetricLightPostProcess = null;
  74737. _this.volumetricLightSmoothXPostProcess = null;
  74738. _this.volumetricLightSmoothYPostProcess = null;
  74739. _this.volumetricLightMergePostProces = null;
  74740. _this.volumetricLightFinalPostProcess = null;
  74741. _this.luminancePostProcess = null;
  74742. _this.luminanceDownSamplePostProcesses = [];
  74743. _this.hdrPostProcess = null;
  74744. _this.textureAdderFinalPostProcess = null;
  74745. _this.lensFlareFinalPostProcess = null;
  74746. _this.hdrFinalPostProcess = null;
  74747. _this.lensFlarePostProcess = null;
  74748. _this.lensFlareComposePostProcess = null;
  74749. _this.motionBlurPostProcess = null;
  74750. _this.depthOfFieldPostProcess = null;
  74751. // Values
  74752. _this.brightThreshold = 1.0;
  74753. _this.blurWidth = 512.0;
  74754. _this.horizontalBlur = false;
  74755. _this.exposure = 1.0;
  74756. _this.lensTexture = null;
  74757. _this.volumetricLightCoefficient = 0.2;
  74758. _this.volumetricLightPower = 4.0;
  74759. _this.volumetricLightBlurScale = 64.0;
  74760. _this.sourceLight = null;
  74761. _this.hdrMinimumLuminance = 1.0;
  74762. _this.hdrDecreaseRate = 0.5;
  74763. _this.hdrIncreaseRate = 0.5;
  74764. _this.lensColorTexture = null;
  74765. _this.lensFlareStrength = 20.0;
  74766. _this.lensFlareGhostDispersal = 1.4;
  74767. _this.lensFlareHaloWidth = 0.7;
  74768. _this.lensFlareDistortionStrength = 16.0;
  74769. _this.lensStarTexture = null;
  74770. _this.lensFlareDirtTexture = null;
  74771. _this.depthOfFieldDistance = 10.0;
  74772. _this.depthOfFieldBlurWidth = 64.0;
  74773. _this.motionStrength = 1.0;
  74774. // IAnimatable
  74775. _this.animations = [];
  74776. _this._currentDepthOfFieldSource = null;
  74777. _this._hdrCurrentLuminance = 1.0;
  74778. // Getters and setters
  74779. _this._bloomEnabled = true;
  74780. _this._depthOfFieldEnabled = false;
  74781. _this._vlsEnabled = false;
  74782. _this._lensFlareEnabled = false;
  74783. _this._hdrEnabled = false;
  74784. _this._motionBlurEnabled = false;
  74785. _this._motionBlurSamples = 64.0;
  74786. _this._volumetricLightStepsCount = 50.0;
  74787. _this._cameras = cameras || [];
  74788. // Initialize
  74789. _this._scene = scene;
  74790. _this._basePostProcess = originalPostProcess;
  74791. _this._ratio = ratio;
  74792. // Misc
  74793. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74794. // Finish
  74795. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74796. _this._buildPipeline();
  74797. return _this;
  74798. }
  74799. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74800. get: function () {
  74801. return this._bloomEnabled;
  74802. },
  74803. set: function (enabled) {
  74804. if (this._bloomEnabled === enabled) {
  74805. return;
  74806. }
  74807. this._bloomEnabled = enabled;
  74808. this._buildPipeline();
  74809. },
  74810. enumerable: true,
  74811. configurable: true
  74812. });
  74813. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74814. get: function () {
  74815. return this._depthOfFieldEnabled;
  74816. },
  74817. set: function (enabled) {
  74818. if (this._depthOfFieldEnabled === enabled) {
  74819. return;
  74820. }
  74821. this._depthOfFieldEnabled = enabled;
  74822. this._buildPipeline();
  74823. },
  74824. enumerable: true,
  74825. configurable: true
  74826. });
  74827. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74828. get: function () {
  74829. return this._lensFlareEnabled;
  74830. },
  74831. set: function (enabled) {
  74832. if (this._lensFlareEnabled === enabled) {
  74833. return;
  74834. }
  74835. this._lensFlareEnabled = enabled;
  74836. this._buildPipeline();
  74837. },
  74838. enumerable: true,
  74839. configurable: true
  74840. });
  74841. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74842. get: function () {
  74843. return this._hdrEnabled;
  74844. },
  74845. set: function (enabled) {
  74846. if (this._hdrEnabled === enabled) {
  74847. return;
  74848. }
  74849. this._hdrEnabled = enabled;
  74850. this._buildPipeline();
  74851. },
  74852. enumerable: true,
  74853. configurable: true
  74854. });
  74855. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74856. get: function () {
  74857. return this._vlsEnabled;
  74858. },
  74859. set: function (enabled) {
  74860. if (this._vlsEnabled === enabled) {
  74861. return;
  74862. }
  74863. if (enabled) {
  74864. var geometry = this._scene.enableGeometryBufferRenderer();
  74865. if (!geometry) {
  74866. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74867. return;
  74868. }
  74869. }
  74870. this._vlsEnabled = enabled;
  74871. this._buildPipeline();
  74872. },
  74873. enumerable: true,
  74874. configurable: true
  74875. });
  74876. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74877. get: function () {
  74878. return this._motionBlurEnabled;
  74879. },
  74880. set: function (enabled) {
  74881. if (this._motionBlurEnabled === enabled) {
  74882. return;
  74883. }
  74884. this._motionBlurEnabled = enabled;
  74885. this._buildPipeline();
  74886. },
  74887. enumerable: true,
  74888. configurable: true
  74889. });
  74890. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74891. get: function () {
  74892. return this._volumetricLightStepsCount;
  74893. },
  74894. set: function (count) {
  74895. if (this.volumetricLightPostProcess) {
  74896. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74897. }
  74898. this._volumetricLightStepsCount = count;
  74899. },
  74900. enumerable: true,
  74901. configurable: true
  74902. });
  74903. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74904. get: function () {
  74905. return this._motionBlurSamples;
  74906. },
  74907. set: function (samples) {
  74908. if (this.motionBlurPostProcess) {
  74909. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74910. }
  74911. this._motionBlurSamples = samples;
  74912. },
  74913. enumerable: true,
  74914. configurable: true
  74915. });
  74916. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74917. var _this = this;
  74918. var ratio = this._ratio;
  74919. var scene = this._scene;
  74920. this._disposePostProcesses();
  74921. this._reset();
  74922. // Create pass post-process
  74923. if (!this._basePostProcess) {
  74924. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74925. this.originalPostProcess.onApply = function (effect) {
  74926. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74927. };
  74928. }
  74929. else {
  74930. this.originalPostProcess = this._basePostProcess;
  74931. }
  74932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74933. this._currentDepthOfFieldSource = this.originalPostProcess;
  74934. if (this._bloomEnabled) {
  74935. // Create down sample X4 post-process
  74936. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74937. // Create bright pass post-process
  74938. this._createBrightPassPostProcess(scene, ratio / 2);
  74939. // Create gaussian blur post-processes (down sampling blurs)
  74940. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74941. // Create texture adder post-process
  74942. this._createTextureAdderPostProcess(scene, ratio);
  74943. // Create depth-of-field source post-process
  74944. 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);
  74945. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74946. }
  74947. if (this._vlsEnabled) {
  74948. // Create volumetric light
  74949. this._createVolumetricLightPostProcess(scene, ratio);
  74950. // Create volumetric light final post-process
  74951. 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);
  74952. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74953. }
  74954. if (this._lensFlareEnabled) {
  74955. // Create lens flare post-process
  74956. this._createLensFlarePostProcess(scene, ratio);
  74957. // Create depth-of-field source post-process post lens-flare and disable it now
  74958. 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);
  74959. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74960. }
  74961. if (this._hdrEnabled) {
  74962. // Create luminance
  74963. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74964. // Create HDR
  74965. this._createHdrPostProcess(scene, ratio);
  74966. // Create depth-of-field source post-process post hdr and disable it now
  74967. 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);
  74968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74969. }
  74970. if (this._depthOfFieldEnabled) {
  74971. // Create gaussian blur used by depth-of-field
  74972. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74973. // Create depth-of-field post-process
  74974. this._createDepthOfFieldPostProcess(scene, ratio);
  74975. }
  74976. if (this._motionBlurEnabled) {
  74977. // Create motion blur post-process
  74978. this._createMotionBlurPostProcess(scene, ratio);
  74979. }
  74980. if (this._cameras !== null) {
  74981. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74982. }
  74983. };
  74984. // Down Sample X4 Post-Processs
  74985. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74986. var _this = this;
  74987. var downSampleX4Offsets = new Array(32);
  74988. 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);
  74989. this.downSampleX4PostProcess.onApply = function (effect) {
  74990. var id = 0;
  74991. var width = _this.downSampleX4PostProcess.width;
  74992. var height = _this.downSampleX4PostProcess.height;
  74993. for (var i = -2; i < 2; i++) {
  74994. for (var j = -2; j < 2; j++) {
  74995. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74996. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74997. id += 2;
  74998. }
  74999. }
  75000. effect.setArray2("dsOffsets", downSampleX4Offsets);
  75001. };
  75002. // Add to pipeline
  75003. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  75004. };
  75005. // Brightpass Post-Process
  75006. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  75007. var _this = this;
  75008. var brightOffsets = new Array(8);
  75009. 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);
  75010. this.brightPassPostProcess.onApply = function (effect) {
  75011. var sU = (1.0 / _this.brightPassPostProcess.width);
  75012. var sV = (1.0 / _this.brightPassPostProcess.height);
  75013. brightOffsets[0] = -0.5 * sU;
  75014. brightOffsets[1] = 0.5 * sV;
  75015. brightOffsets[2] = 0.5 * sU;
  75016. brightOffsets[3] = 0.5 * sV;
  75017. brightOffsets[4] = -0.5 * sU;
  75018. brightOffsets[5] = -0.5 * sV;
  75019. brightOffsets[6] = 0.5 * sU;
  75020. brightOffsets[7] = -0.5 * sV;
  75021. effect.setArray2("dsOffsets", brightOffsets);
  75022. effect.setFloat("brightThreshold", _this.brightThreshold);
  75023. };
  75024. // Add to pipeline
  75025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  75026. };
  75027. // Create blur H&V post-processes
  75028. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  75029. var _this = this;
  75030. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  75031. var engine = scene.getEngine();
  75032. 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);
  75033. 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);
  75034. blurX.onActivateObservable.add(function () {
  75035. var dw = blurX.width / engine.getRenderWidth();
  75036. blurX.kernel = _this[blurWidthKey] * dw;
  75037. });
  75038. blurY.onActivateObservable.add(function () {
  75039. var dw = blurY.height / engine.getRenderHeight();
  75040. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  75041. });
  75042. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  75043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  75044. this.blurHPostProcesses.push(blurX);
  75045. this.blurVPostProcesses.push(blurY);
  75046. };
  75047. // Create texture adder post-process
  75048. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  75049. var _this = this;
  75050. 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);
  75051. this.textureAdderPostProcess.onApply = function (effect) {
  75052. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  75053. effect.setTexture("lensSampler", _this.lensTexture);
  75054. effect.setFloat("exposure", _this.exposure);
  75055. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  75056. };
  75057. // Add to pipeline
  75058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  75059. };
  75060. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  75061. var _this = this;
  75062. var geometryRenderer = scene.enableGeometryBufferRenderer();
  75063. geometryRenderer.enablePosition = true;
  75064. var geometry = geometryRenderer.getGBuffer();
  75065. // Base post-process
  75066. 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));
  75067. var depthValues = BABYLON.Vector2.Zero();
  75068. this.volumetricLightPostProcess.onApply = function (effect) {
  75069. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  75070. var generator = _this.sourceLight.getShadowGenerator();
  75071. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  75072. effect.setTexture("positionSampler", geometry.textures[2]);
  75073. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  75074. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  75075. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  75076. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  75077. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  75078. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  75079. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  75080. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  75081. effect.setVector2("depthValues", depthValues);
  75082. }
  75083. };
  75084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  75085. // Smooth
  75086. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  75087. // Merge
  75088. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  75089. this.volumetricLightMergePostProces.onApply = function (effect) {
  75090. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  75091. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  75092. };
  75093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  75094. };
  75095. // Create luminance
  75096. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  75097. var _this = this;
  75098. // Create luminance
  75099. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  75100. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  75101. var offsets = [];
  75102. this.luminancePostProcess.onApply = function (effect) {
  75103. var sU = (1.0 / _this.luminancePostProcess.width);
  75104. var sV = (1.0 / _this.luminancePostProcess.height);
  75105. offsets[0] = -0.5 * sU;
  75106. offsets[1] = 0.5 * sV;
  75107. offsets[2] = 0.5 * sU;
  75108. offsets[3] = 0.5 * sV;
  75109. offsets[4] = -0.5 * sU;
  75110. offsets[5] = -0.5 * sV;
  75111. offsets[6] = 0.5 * sU;
  75112. offsets[7] = -0.5 * sV;
  75113. effect.setArray2("lumOffsets", offsets);
  75114. };
  75115. // Add to pipeline
  75116. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  75117. // Create down sample luminance
  75118. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  75119. var size = Math.pow(3, i);
  75120. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  75121. if (i === 0) {
  75122. defines += "#define FINAL_DOWN_SAMPLER";
  75123. }
  75124. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  75125. this.luminanceDownSamplePostProcesses.push(postProcess);
  75126. }
  75127. // Create callbacks and add effects
  75128. var lastLuminance = this.luminancePostProcess;
  75129. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  75130. var downSampleOffsets = new Array(18);
  75131. pp.onApply = function (effect) {
  75132. if (!lastLuminance) {
  75133. return;
  75134. }
  75135. var id = 0;
  75136. for (var x = -1; x < 2; x++) {
  75137. for (var y = -1; y < 2; y++) {
  75138. downSampleOffsets[id] = x / lastLuminance.width;
  75139. downSampleOffsets[id + 1] = y / lastLuminance.height;
  75140. id += 2;
  75141. }
  75142. }
  75143. effect.setArray2("dsOffsets", downSampleOffsets);
  75144. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  75145. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75146. lastLuminance = _this.luminancePostProcess;
  75147. }
  75148. else {
  75149. lastLuminance = pp;
  75150. }
  75151. };
  75152. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  75153. pp.onAfterRender = function (effect) {
  75154. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  75155. 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);
  75156. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  75157. };
  75158. }
  75159. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  75160. });
  75161. };
  75162. // Create HDR post-process
  75163. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  75164. var _this = this;
  75165. 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);
  75166. var outputLiminance = 1;
  75167. var time = 0;
  75168. var lastTime = 0;
  75169. this.hdrPostProcess.onApply = function (effect) {
  75170. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  75171. time += scene.getEngine().getDeltaTime();
  75172. if (outputLiminance < 0) {
  75173. outputLiminance = _this._hdrCurrentLuminance;
  75174. }
  75175. else {
  75176. var dt = (lastTime - time) / 1000.0;
  75177. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  75178. outputLiminance += _this.hdrDecreaseRate * dt;
  75179. }
  75180. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  75181. outputLiminance -= _this.hdrIncreaseRate * dt;
  75182. }
  75183. else {
  75184. outputLiminance = _this._hdrCurrentLuminance;
  75185. }
  75186. }
  75187. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  75188. effect.setFloat("averageLuminance", outputLiminance);
  75189. lastTime = time;
  75190. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  75191. };
  75192. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  75193. };
  75194. // Create lens flare post-process
  75195. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  75196. var _this = this;
  75197. 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);
  75198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  75199. this._createBlurPostProcesses(scene, ratio / 4, 2);
  75200. 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);
  75201. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  75202. var resolution = new BABYLON.Vector2(0, 0);
  75203. // Lens flare
  75204. this.lensFlarePostProcess.onApply = function (effect) {
  75205. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  75206. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  75207. effect.setFloat("strength", _this.lensFlareStrength);
  75208. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  75209. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  75210. // Shift
  75211. resolution.x = _this.lensFlarePostProcess.width;
  75212. resolution.y = _this.lensFlarePostProcess.height;
  75213. effect.setVector2("resolution", resolution);
  75214. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  75215. };
  75216. // Compose
  75217. 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);
  75218. 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);
  75219. this.lensFlareComposePostProcess.onApply = function (effect) {
  75220. if (!_this._scene.activeCamera) {
  75221. return;
  75222. }
  75223. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75224. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  75225. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  75226. // Lens start rotation matrix
  75227. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  75228. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  75229. 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));
  75230. camRot *= 4.0;
  75231. 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);
  75232. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75233. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75234. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75235. };
  75236. };
  75237. // Create depth-of-field post-process
  75238. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75239. var _this = this;
  75240. 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);
  75241. this.depthOfFieldPostProcess.onApply = function (effect) {
  75242. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75243. effect.setTexture("depthSampler", _this._getDepthTexture());
  75244. effect.setFloat("distance", _this.depthOfFieldDistance);
  75245. };
  75246. // Add to pipeline
  75247. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75248. };
  75249. // Create motion blur post-process
  75250. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75251. var _this = this;
  75252. 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);
  75253. var motionScale = 0;
  75254. var prevViewProjection = BABYLON.Matrix.Identity();
  75255. var invViewProjection = BABYLON.Matrix.Identity();
  75256. var viewProjection = BABYLON.Matrix.Identity();
  75257. var screenSize = BABYLON.Vector2.Zero();
  75258. this.motionBlurPostProcess.onApply = function (effect) {
  75259. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75260. viewProjection.invertToRef(invViewProjection);
  75261. effect.setMatrix("inverseViewProjection", invViewProjection);
  75262. effect.setMatrix("prevViewProjection", prevViewProjection);
  75263. prevViewProjection = viewProjection;
  75264. screenSize.x = _this.motionBlurPostProcess.width;
  75265. screenSize.y = _this.motionBlurPostProcess.height;
  75266. effect.setVector2("screenSize", screenSize);
  75267. motionScale = scene.getEngine().getFps() / 60.0;
  75268. effect.setFloat("motionScale", motionScale);
  75269. effect.setFloat("motionStrength", _this.motionStrength);
  75270. effect.setTexture("depthSampler", _this._getDepthTexture());
  75271. };
  75272. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75273. };
  75274. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75275. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75276. var renderer = this._scene.enableGeometryBufferRenderer();
  75277. return renderer.getGBuffer().textures[0];
  75278. }
  75279. return this._scene.enableDepthRenderer().getDepthMap();
  75280. };
  75281. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75282. for (var i = 0; i < this._cameras.length; i++) {
  75283. var camera = this._cameras[i];
  75284. if (this.originalPostProcess) {
  75285. this.originalPostProcess.dispose(camera);
  75286. }
  75287. if (this.downSampleX4PostProcess) {
  75288. this.downSampleX4PostProcess.dispose(camera);
  75289. }
  75290. if (this.brightPassPostProcess) {
  75291. this.brightPassPostProcess.dispose(camera);
  75292. }
  75293. if (this.textureAdderPostProcess) {
  75294. this.textureAdderPostProcess.dispose(camera);
  75295. }
  75296. if (this.textureAdderFinalPostProcess) {
  75297. this.textureAdderFinalPostProcess.dispose(camera);
  75298. }
  75299. if (this.volumetricLightPostProcess) {
  75300. this.volumetricLightPostProcess.dispose(camera);
  75301. }
  75302. if (this.volumetricLightSmoothXPostProcess) {
  75303. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75304. }
  75305. if (this.volumetricLightSmoothYPostProcess) {
  75306. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75307. }
  75308. if (this.volumetricLightMergePostProces) {
  75309. this.volumetricLightMergePostProces.dispose(camera);
  75310. }
  75311. if (this.volumetricLightFinalPostProcess) {
  75312. this.volumetricLightFinalPostProcess.dispose(camera);
  75313. }
  75314. if (this.lensFlarePostProcess) {
  75315. this.lensFlarePostProcess.dispose(camera);
  75316. }
  75317. if (this.lensFlareComposePostProcess) {
  75318. this.lensFlareComposePostProcess.dispose(camera);
  75319. }
  75320. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75321. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75322. }
  75323. if (this.luminancePostProcess) {
  75324. this.luminancePostProcess.dispose(camera);
  75325. }
  75326. if (this.hdrPostProcess) {
  75327. this.hdrPostProcess.dispose(camera);
  75328. }
  75329. if (this.hdrFinalPostProcess) {
  75330. this.hdrFinalPostProcess.dispose(camera);
  75331. }
  75332. if (this.depthOfFieldPostProcess) {
  75333. this.depthOfFieldPostProcess.dispose(camera);
  75334. }
  75335. if (this.motionBlurPostProcess) {
  75336. this.motionBlurPostProcess.dispose(camera);
  75337. }
  75338. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75339. this.blurHPostProcesses[j].dispose(camera);
  75340. }
  75341. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75342. this.blurVPostProcesses[j].dispose(camera);
  75343. }
  75344. }
  75345. this.originalPostProcess = null;
  75346. this.downSampleX4PostProcess = null;
  75347. this.brightPassPostProcess = null;
  75348. this.textureAdderPostProcess = null;
  75349. this.textureAdderFinalPostProcess = null;
  75350. this.volumetricLightPostProcess = null;
  75351. this.volumetricLightSmoothXPostProcess = null;
  75352. this.volumetricLightSmoothYPostProcess = null;
  75353. this.volumetricLightMergePostProces = null;
  75354. this.volumetricLightFinalPostProcess = null;
  75355. this.lensFlarePostProcess = null;
  75356. this.lensFlareComposePostProcess = null;
  75357. this.luminancePostProcess = null;
  75358. this.hdrPostProcess = null;
  75359. this.hdrFinalPostProcess = null;
  75360. this.depthOfFieldPostProcess = null;
  75361. this.motionBlurPostProcess = null;
  75362. this.luminanceDownSamplePostProcesses = [];
  75363. this.blurHPostProcesses = [];
  75364. this.blurVPostProcesses = [];
  75365. };
  75366. /**
  75367. * Dispose of the pipeline and stop all post processes
  75368. */
  75369. StandardRenderingPipeline.prototype.dispose = function () {
  75370. this._disposePostProcesses();
  75371. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75372. _super.prototype.dispose.call(this);
  75373. };
  75374. /**
  75375. * Serialize the rendering pipeline (Used when exporting)
  75376. * @returns the serialized object
  75377. */
  75378. StandardRenderingPipeline.prototype.serialize = function () {
  75379. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75380. if (this.sourceLight) {
  75381. serializationObject.sourceLightId = this.sourceLight.id;
  75382. }
  75383. serializationObject.customType = "StandardRenderingPipeline";
  75384. return serializationObject;
  75385. };
  75386. /**
  75387. * Parse the serialized pipeline
  75388. * @param source Source pipeline.
  75389. * @param scene The scene to load the pipeline to.
  75390. * @param rootUrl The URL of the serialized pipeline.
  75391. * @returns An instantiated pipeline from the serialized object.
  75392. */
  75393. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75394. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75395. if (source.sourceLightId) {
  75396. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75397. }
  75398. return p;
  75399. };
  75400. // Luminance steps
  75401. StandardRenderingPipeline.LuminanceSteps = 6;
  75402. __decorate([
  75403. BABYLON.serialize()
  75404. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75405. __decorate([
  75406. BABYLON.serialize()
  75407. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75408. __decorate([
  75409. BABYLON.serialize()
  75410. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75411. __decorate([
  75412. BABYLON.serialize()
  75413. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75414. __decorate([
  75415. BABYLON.serializeAsTexture("lensTexture")
  75416. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75417. __decorate([
  75418. BABYLON.serialize()
  75419. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75420. __decorate([
  75421. BABYLON.serialize()
  75422. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75423. __decorate([
  75424. BABYLON.serialize()
  75425. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75426. __decorate([
  75427. BABYLON.serialize()
  75428. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75429. __decorate([
  75430. BABYLON.serialize()
  75431. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75432. __decorate([
  75433. BABYLON.serialize()
  75434. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75435. __decorate([
  75436. BABYLON.serializeAsTexture("lensColorTexture")
  75437. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75438. __decorate([
  75439. BABYLON.serialize()
  75440. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75441. __decorate([
  75442. BABYLON.serialize()
  75443. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75444. __decorate([
  75445. BABYLON.serialize()
  75446. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75447. __decorate([
  75448. BABYLON.serialize()
  75449. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75450. __decorate([
  75451. BABYLON.serializeAsTexture("lensStarTexture")
  75452. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75453. __decorate([
  75454. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75455. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75456. __decorate([
  75457. BABYLON.serialize()
  75458. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75459. __decorate([
  75460. BABYLON.serialize()
  75461. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75462. __decorate([
  75463. BABYLON.serialize()
  75464. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75465. __decorate([
  75466. BABYLON.serialize()
  75467. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75468. __decorate([
  75469. BABYLON.serialize()
  75470. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75471. __decorate([
  75472. BABYLON.serialize()
  75473. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75474. __decorate([
  75475. BABYLON.serialize()
  75476. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75477. __decorate([
  75478. BABYLON.serialize()
  75479. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75480. __decorate([
  75481. BABYLON.serialize()
  75482. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75483. __decorate([
  75484. BABYLON.serialize()
  75485. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75486. __decorate([
  75487. BABYLON.serialize()
  75488. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75489. __decorate([
  75490. BABYLON.serialize()
  75491. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75492. return StandardRenderingPipeline;
  75493. }(BABYLON.PostProcessRenderPipeline));
  75494. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75495. })(BABYLON || (BABYLON = {}));
  75496. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75497. var BABYLON;
  75498. (function (BABYLON) {
  75499. var FxaaPostProcess = /** @class */ (function (_super) {
  75500. __extends(FxaaPostProcess, _super);
  75501. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75502. if (camera === void 0) { camera = null; }
  75503. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75504. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75505. var defines = _this._getDefines();
  75506. _this.updateEffect(defines);
  75507. _this.onApplyObservable.add(function (effect) {
  75508. var texelSize = _this.texelSize;
  75509. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75510. });
  75511. return _this;
  75512. }
  75513. FxaaPostProcess.prototype._getDefines = function () {
  75514. var engine = this.getEngine();
  75515. if (!engine) {
  75516. return null;
  75517. }
  75518. var glInfo = engine.getGlInfo();
  75519. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75520. return "#define MALI 1\n";
  75521. }
  75522. return null;
  75523. };
  75524. return FxaaPostProcess;
  75525. }(BABYLON.PostProcess));
  75526. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75527. })(BABYLON || (BABYLON = {}));
  75528. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75529. var BABYLON;
  75530. (function (BABYLON) {
  75531. /**
  75532. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75533. */
  75534. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75535. __extends(ChromaticAberrationPostProcess, _super);
  75536. /**
  75537. * Creates a new instance ChromaticAberrationPostProcess
  75538. * @param name The name of the effect.
  75539. * @param screenWidth The width of the screen to apply the effect on.
  75540. * @param screenHeight The height of the screen to apply the effect on.
  75541. * @param options The required width/height ratio to downsize to before computing the render pass.
  75542. * @param camera The camera to apply the render pass to.
  75543. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75544. * @param engine The engine which the post process will be applied. (default: current engine)
  75545. * @param reusable If the post process can be reused on the same frame. (default: false)
  75546. * @param textureType Type of textures used when performing the post process. (default: 0)
  75547. * @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)
  75548. */
  75549. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75550. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75551. if (blockCompilation === void 0) { blockCompilation = false; }
  75552. 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;
  75553. /**
  75554. * The amount of seperation of rgb channels (default: 30)
  75555. */
  75556. _this.aberrationAmount = 30;
  75557. /**
  75558. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75559. */
  75560. _this.radialIntensity = 0;
  75561. /**
  75562. * 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))
  75563. */
  75564. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75565. /**
  75566. * 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))
  75567. */
  75568. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75569. _this.onApplyObservable.add(function (effect) {
  75570. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75571. effect.setFloat('screen_width', screenWidth);
  75572. effect.setFloat('screen_height', screenHeight);
  75573. effect.setFloat('radialIntensity', _this.radialIntensity);
  75574. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75575. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75576. });
  75577. return _this;
  75578. }
  75579. return ChromaticAberrationPostProcess;
  75580. }(BABYLON.PostProcess));
  75581. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75582. })(BABYLON || (BABYLON = {}));
  75583. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75584. var BABYLON;
  75585. (function (BABYLON) {
  75586. /**
  75587. * The GrainPostProcess adds noise to the image at mid luminance levels
  75588. */
  75589. var GrainPostProcess = /** @class */ (function (_super) {
  75590. __extends(GrainPostProcess, _super);
  75591. /**
  75592. * Creates a new instance of @see GrainPostProcess
  75593. * @param name The name of the effect.
  75594. * @param options The required width/height ratio to downsize to before computing the render pass.
  75595. * @param camera The camera to apply the render pass to.
  75596. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75597. * @param engine The engine which the post process will be applied. (default: current engine)
  75598. * @param reusable If the post process can be reused on the same frame. (default: false)
  75599. * @param textureType Type of textures used when performing the post process. (default: 0)
  75600. * @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)
  75601. */
  75602. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75603. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75604. if (blockCompilation === void 0) { blockCompilation = false; }
  75605. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75606. /**
  75607. * The intensity of the grain added (default: 30)
  75608. */
  75609. _this.intensity = 30;
  75610. /**
  75611. * If the grain should be randomized on every frame
  75612. */
  75613. _this.animated = false;
  75614. _this.onApplyObservable.add(function (effect) {
  75615. effect.setFloat('intensity', _this.intensity);
  75616. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75617. });
  75618. return _this;
  75619. }
  75620. return GrainPostProcess;
  75621. }(BABYLON.PostProcess));
  75622. BABYLON.GrainPostProcess = GrainPostProcess;
  75623. })(BABYLON || (BABYLON = {}));
  75624. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75625. var BABYLON;
  75626. (function (BABYLON) {
  75627. /**
  75628. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75629. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75630. */
  75631. var SharpenPostProcess = /** @class */ (function (_super) {
  75632. __extends(SharpenPostProcess, _super);
  75633. /**
  75634. * Creates a new instance ConvolutionPostProcess
  75635. * @param name The name of the effect.
  75636. * @param options The required width/height ratio to downsize to before computing the render pass.
  75637. * @param camera The camera to apply the render pass to.
  75638. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75639. * @param engine The engine which the post process will be applied. (default: current engine)
  75640. * @param reusable If the post process can be reused on the same frame. (default: false)
  75641. * @param textureType Type of textures used when performing the post process. (default: 0)
  75642. * @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)
  75643. */
  75644. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75645. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75646. if (blockCompilation === void 0) { blockCompilation = false; }
  75647. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75648. /**
  75649. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75650. */
  75651. _this.colorAmount = 1.0;
  75652. /**
  75653. * How much sharpness should be applied (default: 0.3)
  75654. */
  75655. _this.edgeAmount = 0.3;
  75656. _this.onApply = function (effect) {
  75657. effect.setFloat2("screenSize", _this.width, _this.height);
  75658. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75659. };
  75660. return _this;
  75661. }
  75662. return SharpenPostProcess;
  75663. }(BABYLON.PostProcess));
  75664. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75665. })(BABYLON || (BABYLON = {}));
  75666. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75667. var BABYLON;
  75668. (function (BABYLON) {
  75669. /**
  75670. * The Blur Post Process which blurs an image based on a kernel and direction.
  75671. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75672. */
  75673. var BlurPostProcess = /** @class */ (function (_super) {
  75674. __extends(BlurPostProcess, _super);
  75675. /**
  75676. * Creates a new instance BlurPostProcess
  75677. * @param name The name of the effect.
  75678. * @param direction The direction in which to blur the image.
  75679. * @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.
  75680. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75681. * @param camera The camera to apply the render pass to.
  75682. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75683. * @param engine The engine which the post process will be applied. (default: current engine)
  75684. * @param reusable If the post process can be reused on the same frame. (default: false)
  75685. * @param textureType Type of textures used when performing the post process. (default: 0)
  75686. * @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)
  75687. */
  75688. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75690. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75691. if (defines === void 0) { defines = ""; }
  75692. if (blockCompilation === void 0) { blockCompilation = false; }
  75693. 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;
  75694. _this.direction = direction;
  75695. _this.blockCompilation = blockCompilation;
  75696. _this._packedFloat = false;
  75697. _this._staticDefines = "";
  75698. _this._staticDefines = defines;
  75699. _this.onApplyObservable.add(function (effect) {
  75700. if (_this._outputTexture) {
  75701. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75702. }
  75703. else {
  75704. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75705. }
  75706. });
  75707. _this.kernel = kernel;
  75708. return _this;
  75709. }
  75710. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75711. /**
  75712. * Gets the length in pixels of the blur sample region
  75713. */
  75714. get: function () {
  75715. return this._idealKernel;
  75716. },
  75717. /**
  75718. * Sets the length in pixels of the blur sample region
  75719. */
  75720. set: function (v) {
  75721. if (this._idealKernel === v) {
  75722. return;
  75723. }
  75724. v = Math.max(v, 1);
  75725. this._idealKernel = v;
  75726. this._kernel = this._nearestBestKernel(v);
  75727. if (!this.blockCompilation) {
  75728. this._updateParameters();
  75729. }
  75730. },
  75731. enumerable: true,
  75732. configurable: true
  75733. });
  75734. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75735. /**
  75736. * Gets wether or not the blur is unpacking/repacking floats
  75737. */
  75738. get: function () {
  75739. return this._packedFloat;
  75740. },
  75741. /**
  75742. * Sets wether or not the blur needs to unpack/repack floats
  75743. */
  75744. set: function (v) {
  75745. if (this._packedFloat === v) {
  75746. return;
  75747. }
  75748. this._packedFloat = v;
  75749. if (!this.blockCompilation) {
  75750. this._updateParameters();
  75751. }
  75752. },
  75753. enumerable: true,
  75754. configurable: true
  75755. });
  75756. /**
  75757. * Updates the effect with the current post process compile time values and recompiles the shader.
  75758. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75759. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75760. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75761. * @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
  75762. * @param onCompiled Called when the shader has been compiled.
  75763. * @param onError Called if there is an error when compiling a shader.
  75764. */
  75765. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75766. if (defines === void 0) { defines = null; }
  75767. if (uniforms === void 0) { uniforms = null; }
  75768. if (samplers === void 0) { samplers = null; }
  75769. this._updateParameters(onCompiled, onError);
  75770. };
  75771. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75772. // Generate sampling offsets and weights
  75773. var N = this._kernel;
  75774. var centerIndex = (N - 1) / 2;
  75775. // Generate Gaussian sampling weights over kernel
  75776. var offsets = [];
  75777. var weights = [];
  75778. var totalWeight = 0;
  75779. for (var i = 0; i < N; i++) {
  75780. var u = i / (N - 1);
  75781. var w = this._gaussianWeight(u * 2.0 - 1);
  75782. offsets[i] = (i - centerIndex);
  75783. weights[i] = w;
  75784. totalWeight += w;
  75785. }
  75786. // Normalize weights
  75787. for (var i = 0; i < weights.length; i++) {
  75788. weights[i] /= totalWeight;
  75789. }
  75790. // Optimize: combine samples to take advantage of hardware linear sampling
  75791. // Walk from left to center, combining pairs (symmetrically)
  75792. var linearSamplingWeights = [];
  75793. var linearSamplingOffsets = [];
  75794. var linearSamplingMap = [];
  75795. for (var i = 0; i <= centerIndex; i += 2) {
  75796. var j = Math.min(i + 1, Math.floor(centerIndex));
  75797. var singleCenterSample = i === j;
  75798. if (singleCenterSample) {
  75799. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75800. }
  75801. else {
  75802. var sharedCell = j === centerIndex;
  75803. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75804. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75805. if (offsetLinear === 0) {
  75806. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75807. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75808. }
  75809. else {
  75810. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75811. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75812. }
  75813. }
  75814. }
  75815. for (var i = 0; i < linearSamplingMap.length; i++) {
  75816. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75817. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75818. }
  75819. // Replace with optimized
  75820. offsets = linearSamplingOffsets;
  75821. weights = linearSamplingWeights;
  75822. // Generate shaders
  75823. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75824. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75825. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75826. var defines = "";
  75827. defines += this._staticDefines;
  75828. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75829. if (this._staticDefines.indexOf("DOF") != -1) {
  75830. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75831. varyingCount--;
  75832. }
  75833. for (var i = 0; i < varyingCount; i++) {
  75834. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75835. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75836. }
  75837. var depCount = 0;
  75838. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75839. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75840. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75841. depCount++;
  75842. }
  75843. if (this.packedFloat) {
  75844. defines += "#define PACKEDFLOAT 1";
  75845. }
  75846. this.blockCompilation = false;
  75847. _super.prototype.updateEffect.call(this, defines, null, null, {
  75848. varyingCount: varyingCount,
  75849. depCount: depCount
  75850. }, onCompiled, onError);
  75851. };
  75852. /**
  75853. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75854. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75855. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75856. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75857. * The gaps between physical kernels are compensated for in the weighting of the samples
  75858. * @param idealKernel Ideal blur kernel.
  75859. * @return Nearest best kernel.
  75860. */
  75861. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75862. var v = Math.round(idealKernel);
  75863. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75864. var k = _a[_i];
  75865. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75866. return Math.max(k, 3);
  75867. }
  75868. }
  75869. return Math.max(v, 3);
  75870. };
  75871. /**
  75872. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75873. * @param x The point on the Gaussian distribution to sample.
  75874. * @return the value of the Gaussian function at x.
  75875. */
  75876. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75877. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75878. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75879. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75880. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75881. // truncated at around 1.3% of peak strength.
  75882. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75883. var sigma = (1 / 3);
  75884. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75885. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75886. var weight = (1.0 / denominator) * Math.exp(exponent);
  75887. return weight;
  75888. };
  75889. /**
  75890. * Generates a string that can be used as a floating point number in GLSL.
  75891. * @param x Value to print.
  75892. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75893. * @return GLSL float string.
  75894. */
  75895. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75896. if (decimalFigures === void 0) { decimalFigures = 8; }
  75897. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75898. };
  75899. return BlurPostProcess;
  75900. }(BABYLON.PostProcess));
  75901. BABYLON.BlurPostProcess = BlurPostProcess;
  75902. })(BABYLON || (BABYLON = {}));
  75903. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75904. var BABYLON;
  75905. (function (BABYLON) {
  75906. /**
  75907. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75908. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75909. * based on samples that have a large difference in distance than the center pixel.
  75910. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75911. */
  75912. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75913. __extends(DepthOfFieldBlurPostProcess, _super);
  75914. /**
  75915. * Creates a new instance CircleOfConfusionPostProcess
  75916. * @param name The name of the effect.
  75917. * @param scene The scene the effect belongs to.
  75918. * @param direction The direction the blur should be applied.
  75919. * @param kernel The size of the kernel used to blur.
  75920. * @param options The required width/height ratio to downsize to before computing the render pass.
  75921. * @param camera The camera to apply the render pass to.
  75922. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75923. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75924. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75925. * @param engine The engine which the post process will be applied. (default: current engine)
  75926. * @param reusable If the post process can be reused on the same frame. (default: false)
  75927. * @param textureType Type of textures used when performing the post process. (default: 0)
  75928. * @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)
  75929. */
  75930. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75931. if (imageToBlur === void 0) { imageToBlur = null; }
  75932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75933. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75934. if (blockCompilation === void 0) { blockCompilation = false; }
  75935. 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;
  75936. _this.direction = direction;
  75937. _this.onApplyObservable.add(function (effect) {
  75938. if (imageToBlur != null) {
  75939. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75940. }
  75941. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75942. if (scene.activeCamera) {
  75943. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75944. }
  75945. });
  75946. return _this;
  75947. }
  75948. return DepthOfFieldBlurPostProcess;
  75949. }(BABYLON.BlurPostProcess));
  75950. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75951. })(BABYLON || (BABYLON = {}));
  75952. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75953. var BABYLON;
  75954. (function (BABYLON) {
  75955. /**
  75956. * Options to be set when merging outputs from the default pipeline.
  75957. */
  75958. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75959. function DepthOfFieldMergePostProcessOptions() {
  75960. }
  75961. return DepthOfFieldMergePostProcessOptions;
  75962. }());
  75963. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75964. /**
  75965. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75966. */
  75967. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75968. __extends(DepthOfFieldMergePostProcess, _super);
  75969. /**
  75970. * Creates a new instance of DepthOfFieldMergePostProcess
  75971. * @param name The name of the effect.
  75972. * @param originalFromInput Post process which's input will be used for the merge.
  75973. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75974. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75975. * @param options The required width/height ratio to downsize to before computing the render pass.
  75976. * @param camera The camera to apply the render pass to.
  75977. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75978. * @param engine The engine which the post process will be applied. (default: current engine)
  75979. * @param reusable If the post process can be reused on the same frame. (default: false)
  75980. * @param textureType Type of textures used when performing the post process. (default: 0)
  75981. * @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)
  75982. */
  75983. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75984. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75985. if (blockCompilation === void 0) { blockCompilation = false; }
  75986. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75987. _this.blurSteps = blurSteps;
  75988. _this.onApplyObservable.add(function (effect) {
  75989. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75990. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75991. blurSteps.forEach(function (step, index) {
  75992. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75993. });
  75994. });
  75995. if (!blockCompilation) {
  75996. _this.updateEffect();
  75997. }
  75998. return _this;
  75999. }
  76000. /**
  76001. * Updates the effect with the current post process compile time values and recompiles the shader.
  76002. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  76003. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  76004. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  76005. * @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
  76006. * @param onCompiled Called when the shader has been compiled.
  76007. * @param onError Called if there is an error when compiling a shader.
  76008. */
  76009. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  76010. if (defines === void 0) { defines = null; }
  76011. if (uniforms === void 0) { uniforms = null; }
  76012. if (samplers === void 0) { samplers = null; }
  76013. if (!defines) {
  76014. defines = "";
  76015. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  76016. }
  76017. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  76018. };
  76019. return DepthOfFieldMergePostProcess;
  76020. }(BABYLON.PostProcess));
  76021. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  76022. })(BABYLON || (BABYLON = {}));
  76023. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  76024. var BABYLON;
  76025. (function (BABYLON) {
  76026. /**
  76027. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  76028. */
  76029. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  76030. __extends(CircleOfConfusionPostProcess, _super);
  76031. /**
  76032. * Creates a new instance CircleOfConfusionPostProcess
  76033. * @param name The name of the effect.
  76034. * @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.
  76035. * @param options The required width/height ratio to downsize to before computing the render pass.
  76036. * @param camera The camera to apply the render pass to.
  76037. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76038. * @param engine The engine which the post process will be applied. (default: current engine)
  76039. * @param reusable If the post process can be reused on the same frame. (default: false)
  76040. * @param textureType Type of textures used when performing the post process. (default: 0)
  76041. * @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)
  76042. */
  76043. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76044. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76045. if (blockCompilation === void 0) { blockCompilation = false; }
  76046. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76047. /**
  76048. * 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.
  76049. */
  76050. _this.lensSize = 50;
  76051. /**
  76052. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76053. */
  76054. _this.fStop = 1.4;
  76055. /**
  76056. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76057. */
  76058. _this.focusDistance = 2000;
  76059. /**
  76060. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  76061. */
  76062. _this.focalLength = 50;
  76063. _this._depthTexture = null;
  76064. _this._depthTexture = depthTexture;
  76065. _this.onApplyObservable.add(function (effect) {
  76066. if (!_this._depthTexture) {
  76067. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  76068. return;
  76069. }
  76070. effect.setTexture("depthSampler", _this._depthTexture);
  76071. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  76072. var aperture = _this.lensSize / _this.fStop;
  76073. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  76074. effect.setFloat('focusDistance', _this.focusDistance);
  76075. effect.setFloat('cocPrecalculation', cocPrecalculation);
  76076. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  76077. });
  76078. return _this;
  76079. }
  76080. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  76081. /**
  76082. * 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.
  76083. */
  76084. set: function (value) {
  76085. this._depthTexture = value;
  76086. },
  76087. enumerable: true,
  76088. configurable: true
  76089. });
  76090. return CircleOfConfusionPostProcess;
  76091. }(BABYLON.PostProcess));
  76092. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  76093. })(BABYLON || (BABYLON = {}));
  76094. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  76095. var BABYLON;
  76096. (function (BABYLON) {
  76097. /**
  76098. * Specifies the level of max blur that should be applied when using the depth of field effect
  76099. */
  76100. var DepthOfFieldEffectBlurLevel;
  76101. (function (DepthOfFieldEffectBlurLevel) {
  76102. /**
  76103. * Subtle blur
  76104. */
  76105. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  76106. /**
  76107. * Medium blur
  76108. */
  76109. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  76110. /**
  76111. * Large blur
  76112. */
  76113. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  76114. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  76115. ;
  76116. /**
  76117. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  76118. */
  76119. var DepthOfFieldEffect = /** @class */ (function (_super) {
  76120. __extends(DepthOfFieldEffect, _super);
  76121. /**
  76122. * Creates a new instance DepthOfFieldEffect
  76123. * @param scene The scene the effect belongs to.
  76124. * @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.
  76125. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76126. * @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)
  76127. */
  76128. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  76129. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  76130. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76131. if (blockCompilation === void 0) { blockCompilation = false; }
  76132. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  76133. return _this._effects;
  76134. }, true) || this;
  76135. /**
  76136. * Internal post processes in depth of field effect
  76137. */
  76138. _this._effects = [];
  76139. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  76140. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76141. // 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)
  76142. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  76143. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  76144. _this._depthOfFieldBlurY = [];
  76145. _this._depthOfFieldBlurX = [];
  76146. var blurCount = 1;
  76147. var kernelSize = 15;
  76148. switch (blurLevel) {
  76149. case DepthOfFieldEffectBlurLevel.High: {
  76150. blurCount = 3;
  76151. kernelSize = 51;
  76152. break;
  76153. }
  76154. case DepthOfFieldEffectBlurLevel.Medium: {
  76155. blurCount = 2;
  76156. kernelSize = 31;
  76157. break;
  76158. }
  76159. default: {
  76160. kernelSize = 15;
  76161. blurCount = 1;
  76162. break;
  76163. }
  76164. }
  76165. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  76166. var ratio = 1.0;
  76167. for (var i = 0; i < blurCount; i++) {
  76168. 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);
  76169. blurY.autoClear = false;
  76170. ratio = 0.75 / Math.pow(2, i);
  76171. 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);
  76172. blurX.autoClear = false;
  76173. _this._depthOfFieldBlurY.push(blurY);
  76174. _this._depthOfFieldBlurX.push(blurX);
  76175. }
  76176. // Set all post processes on the effect.
  76177. _this._effects = [_this._circleOfConfusion];
  76178. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  76179. _this._effects.push(_this._depthOfFieldBlurY[i]);
  76180. _this._effects.push(_this._depthOfFieldBlurX[i]);
  76181. }
  76182. // Merge blurred images with original image based on circleOfConfusion
  76183. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76184. _this._dofMerge.autoClear = false;
  76185. _this._effects.push(_this._dofMerge);
  76186. return _this;
  76187. }
  76188. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  76189. get: function () {
  76190. return this._circleOfConfusion.focalLength;
  76191. },
  76192. /**
  76193. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  76194. */
  76195. set: function (value) {
  76196. this._circleOfConfusion.focalLength = value;
  76197. },
  76198. enumerable: true,
  76199. configurable: true
  76200. });
  76201. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  76202. get: function () {
  76203. return this._circleOfConfusion.fStop;
  76204. },
  76205. /**
  76206. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  76207. */
  76208. set: function (value) {
  76209. this._circleOfConfusion.fStop = value;
  76210. },
  76211. enumerable: true,
  76212. configurable: true
  76213. });
  76214. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  76215. get: function () {
  76216. return this._circleOfConfusion.focusDistance;
  76217. },
  76218. /**
  76219. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  76220. */
  76221. set: function (value) {
  76222. this._circleOfConfusion.focusDistance = value;
  76223. },
  76224. enumerable: true,
  76225. configurable: true
  76226. });
  76227. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  76228. get: function () {
  76229. return this._circleOfConfusion.lensSize;
  76230. },
  76231. /**
  76232. * 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.
  76233. */
  76234. set: function (value) {
  76235. this._circleOfConfusion.lensSize = value;
  76236. },
  76237. enumerable: true,
  76238. configurable: true
  76239. });
  76240. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76241. /**
  76242. * 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.
  76243. */
  76244. set: function (value) {
  76245. this._circleOfConfusion.depthTexture = value;
  76246. },
  76247. enumerable: true,
  76248. configurable: true
  76249. });
  76250. /**
  76251. * Disposes each of the internal effects for a given camera.
  76252. * @param camera The camera to dispose the effect on.
  76253. */
  76254. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76255. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76256. this._effects[effectIndex].dispose(camera);
  76257. }
  76258. };
  76259. /**
  76260. * Internal
  76261. */
  76262. DepthOfFieldEffect.prototype._updateEffects = function () {
  76263. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76264. this._effects[effectIndex].updateEffect();
  76265. }
  76266. };
  76267. /**
  76268. * Internal
  76269. * @returns if all the contained post processes are ready.
  76270. */
  76271. DepthOfFieldEffect.prototype._isReady = function () {
  76272. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76273. if (!this._effects[effectIndex].isReady()) {
  76274. return false;
  76275. }
  76276. }
  76277. return true;
  76278. };
  76279. return DepthOfFieldEffect;
  76280. }(BABYLON.PostProcessRenderEffect));
  76281. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76282. })(BABYLON || (BABYLON = {}));
  76283. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76284. var BABYLON;
  76285. (function (BABYLON) {
  76286. /**
  76287. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76288. */
  76289. var BloomMergePostProcess = /** @class */ (function (_super) {
  76290. __extends(BloomMergePostProcess, _super);
  76291. /**
  76292. * Creates a new instance of @see BloomMergePostProcess
  76293. * @param name The name of the effect.
  76294. * @param originalFromInput Post process which's input will be used for the merge.
  76295. * @param blurred Blurred highlights post process which's output will be used.
  76296. * @param weight Weight of the bloom to be added to the original input.
  76297. * @param options The required width/height ratio to downsize to before computing the render pass.
  76298. * @param camera The camera to apply the render pass to.
  76299. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76300. * @param engine The engine which the post process will be applied. (default: current engine)
  76301. * @param reusable If the post process can be reused on the same frame. (default: false)
  76302. * @param textureType Type of textures used when performing the post process. (default: 0)
  76303. * @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)
  76304. */
  76305. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76306. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76307. if (blockCompilation === void 0) { blockCompilation = false; }
  76308. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76309. _this.weight = weight;
  76310. _this.onApplyObservable.add(function (effect) {
  76311. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76312. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76313. effect.setFloat("bloomWeight", _this.weight);
  76314. });
  76315. if (!blockCompilation) {
  76316. _this.updateEffect();
  76317. }
  76318. return _this;
  76319. }
  76320. return BloomMergePostProcess;
  76321. }(BABYLON.PostProcess));
  76322. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76323. })(BABYLON || (BABYLON = {}));
  76324. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76325. var BABYLON;
  76326. (function (BABYLON) {
  76327. /**
  76328. * 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.
  76329. */
  76330. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76331. __extends(ExtractHighlightsPostProcess, _super);
  76332. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76333. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76334. if (blockCompilation === void 0) { blockCompilation = false; }
  76335. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76336. /**
  76337. * The luminance threshold, pixels below this value will be set to black.
  76338. */
  76339. _this.threshold = 0.9;
  76340. /**
  76341. * Internal
  76342. */
  76343. _this._exposure = 1;
  76344. /**
  76345. * Post process which has the input texture to be used when performing highlight extraction
  76346. */
  76347. _this._inputPostProcess = null;
  76348. _this.onApplyObservable.add(function (effect) {
  76349. if (_this._inputPostProcess) {
  76350. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76351. }
  76352. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76353. effect.setFloat('exposure', _this._exposure);
  76354. });
  76355. return _this;
  76356. }
  76357. return ExtractHighlightsPostProcess;
  76358. }(BABYLON.PostProcess));
  76359. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76360. })(BABYLON || (BABYLON = {}));
  76361. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76362. var BABYLON;
  76363. (function (BABYLON) {
  76364. /**
  76365. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76366. */
  76367. var BloomEffect = /** @class */ (function (_super) {
  76368. __extends(BloomEffect, _super);
  76369. /**
  76370. * Creates a new instance of @see BloomEffect
  76371. * @param scene The scene the effect belongs to.
  76372. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76373. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76374. * @param bloomWeight The the strength of bloom.
  76375. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76376. * @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)
  76377. */
  76378. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76379. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76380. if (blockCompilation === void 0) { blockCompilation = false; }
  76381. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76382. return _this._effects;
  76383. }, true) || this;
  76384. _this.bloomScale = bloomScale;
  76385. /**
  76386. * Internal
  76387. */
  76388. _this._effects = [];
  76389. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76390. _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);
  76391. _this._blurX.alwaysForcePOT = true;
  76392. _this._blurX.autoClear = false;
  76393. _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);
  76394. _this._blurY.alwaysForcePOT = true;
  76395. _this._blurY.autoClear = false;
  76396. _this.kernel = bloomKernel;
  76397. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76398. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76399. _this._merge.autoClear = false;
  76400. _this._effects.push(_this._merge);
  76401. return _this;
  76402. }
  76403. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76404. /**
  76405. * The luminance threshold to find bright areas of the image to bloom.
  76406. */
  76407. get: function () {
  76408. return this._downscale.threshold;
  76409. },
  76410. set: function (value) {
  76411. this._downscale.threshold = value;
  76412. },
  76413. enumerable: true,
  76414. configurable: true
  76415. });
  76416. Object.defineProperty(BloomEffect.prototype, "weight", {
  76417. /**
  76418. * The strength of the bloom.
  76419. */
  76420. get: function () {
  76421. return this._merge.weight;
  76422. },
  76423. set: function (value) {
  76424. this._merge.weight = value;
  76425. },
  76426. enumerable: true,
  76427. configurable: true
  76428. });
  76429. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76430. /**
  76431. * Specifies the size of the bloom blur kernel, relative to the final output size
  76432. */
  76433. get: function () {
  76434. return this._blurX.kernel / this.bloomScale;
  76435. },
  76436. set: function (value) {
  76437. this._blurX.kernel = value * this.bloomScale;
  76438. this._blurY.kernel = value * this.bloomScale;
  76439. },
  76440. enumerable: true,
  76441. configurable: true
  76442. });
  76443. /**
  76444. * Disposes each of the internal effects for a given camera.
  76445. * @param camera The camera to dispose the effect on.
  76446. */
  76447. BloomEffect.prototype.disposeEffects = function (camera) {
  76448. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76449. this._effects[effectIndex].dispose(camera);
  76450. }
  76451. };
  76452. /**
  76453. * Internal
  76454. */
  76455. BloomEffect.prototype._updateEffects = function () {
  76456. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76457. this._effects[effectIndex].updateEffect();
  76458. }
  76459. };
  76460. /**
  76461. * Internal
  76462. * @returns if all the contained post processes are ready.
  76463. */
  76464. BloomEffect.prototype._isReady = function () {
  76465. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76466. if (!this._effects[effectIndex].isReady()) {
  76467. return false;
  76468. }
  76469. }
  76470. return true;
  76471. };
  76472. return BloomEffect;
  76473. }(BABYLON.PostProcessRenderEffect));
  76474. BABYLON.BloomEffect = BloomEffect;
  76475. })(BABYLON || (BABYLON = {}));
  76476. //# sourceMappingURL=babylon.bloomEffect.js.map
  76477. var BABYLON;
  76478. (function (BABYLON) {
  76479. /**
  76480. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76481. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76482. */
  76483. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76484. __extends(DefaultRenderingPipeline, _super);
  76485. /**
  76486. * @constructor
  76487. * @param {string} name - The rendering pipeline name (default: "")
  76488. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76489. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76490. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76491. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76492. */
  76493. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76494. if (name === void 0) { name = ""; }
  76495. if (hdr === void 0) { hdr = true; }
  76496. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76497. if (automaticBuild === void 0) { automaticBuild = true; }
  76498. var _this = _super.call(this, scene.getEngine(), name) || this;
  76499. _this._camerasToBeAttached = [];
  76500. /**
  76501. * ID of the sharpen post process,
  76502. */
  76503. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76504. /**
  76505. * ID of the image processing post process;
  76506. */
  76507. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76508. /**
  76509. * ID of the Fast Approximate Anti-Aliasing post process;
  76510. */
  76511. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76512. /**
  76513. * ID of the chromatic aberration post process,
  76514. */
  76515. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76516. /**
  76517. * ID of the grain post process
  76518. */
  76519. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76520. /**
  76521. * Glow post process which adds a glow to emmisive areas of the image
  76522. */
  76523. _this._glowLayer = null;
  76524. /**
  76525. * Animations which can be used to tweak settings over a period of time
  76526. */
  76527. _this.animations = [];
  76528. _this._imageProcessingConfigurationObserver = null;
  76529. // Values
  76530. _this._sharpenEnabled = false;
  76531. _this._bloomEnabled = false;
  76532. _this._depthOfFieldEnabled = false;
  76533. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76534. _this._fxaaEnabled = false;
  76535. _this._imageProcessingEnabled = true;
  76536. _this._bloomScale = 0.5;
  76537. _this._chromaticAberrationEnabled = false;
  76538. _this._grainEnabled = false;
  76539. _this._buildAllowed = true;
  76540. _this._resizeObserver = null;
  76541. _this._hardwareScaleLevel = 1.0;
  76542. _this._bloomKernel = 64;
  76543. /**
  76544. * Specifies the weight of the bloom in the final rendering
  76545. */
  76546. _this._bloomWeight = 0.15;
  76547. /**
  76548. * Specifies the luma threshold for the area that will be blurred by the bloom
  76549. */
  76550. _this._bloomThreshold = 0.9;
  76551. _this._samples = 1;
  76552. _this._hasCleared = false;
  76553. _this._prevPostProcess = null;
  76554. _this._prevPrevPostProcess = null;
  76555. _this._cameras = cameras || scene.cameras;
  76556. _this._camerasToBeAttached = _this._cameras.slice();
  76557. _this._buildAllowed = automaticBuild;
  76558. // Initialize
  76559. _this._scene = scene;
  76560. var caps = _this._scene.getEngine().getCaps();
  76561. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76562. // Misc
  76563. if (_this._hdr) {
  76564. if (caps.textureHalfFloatRender) {
  76565. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76566. }
  76567. else if (caps.textureFloatRender) {
  76568. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76569. }
  76570. }
  76571. else {
  76572. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76573. }
  76574. // Attach
  76575. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76576. var engine = _this._scene.getEngine();
  76577. // Create post processes before hand so they can be modified before enabled.
  76578. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76579. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76580. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76581. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76582. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76583. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76584. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76585. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76586. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76587. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76588. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76589. _this.bloomKernel = _this.bloomKernel;
  76590. });
  76591. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76592. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76593. });
  76594. _this._buildPipeline();
  76595. return _this;
  76596. }
  76597. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76598. get: function () {
  76599. return this._sharpenEnabled;
  76600. },
  76601. /**
  76602. * Enable or disable the sharpen process from the pipeline
  76603. */
  76604. set: function (enabled) {
  76605. if (this._sharpenEnabled === enabled) {
  76606. return;
  76607. }
  76608. this._sharpenEnabled = enabled;
  76609. this._buildPipeline();
  76610. },
  76611. enumerable: true,
  76612. configurable: true
  76613. });
  76614. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76615. /**
  76616. * Specifies the size of the bloom blur kernel, relative to the final output size
  76617. */
  76618. get: function () {
  76619. return this._bloomKernel;
  76620. },
  76621. set: function (value) {
  76622. this._bloomKernel = value;
  76623. this.bloom.kernel = value / this._hardwareScaleLevel;
  76624. },
  76625. enumerable: true,
  76626. configurable: true
  76627. });
  76628. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76629. get: function () {
  76630. return this._bloomWeight;
  76631. },
  76632. /**
  76633. * The strength of the bloom.
  76634. */
  76635. set: function (value) {
  76636. if (this._bloomWeight === value) {
  76637. return;
  76638. }
  76639. this.bloom.weight = value;
  76640. this._bloomWeight = value;
  76641. },
  76642. enumerable: true,
  76643. configurable: true
  76644. });
  76645. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76646. get: function () {
  76647. return this._bloomThreshold;
  76648. },
  76649. /**
  76650. * The strength of the bloom.
  76651. */
  76652. set: function (value) {
  76653. if (this._bloomThreshold === value) {
  76654. return;
  76655. }
  76656. this.bloom.threshold = value;
  76657. this._bloomThreshold = value;
  76658. },
  76659. enumerable: true,
  76660. configurable: true
  76661. });
  76662. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76663. get: function () {
  76664. return this._bloomScale;
  76665. },
  76666. /**
  76667. * The scale of the bloom, lower value will provide better performance.
  76668. */
  76669. set: function (value) {
  76670. if (this._bloomScale === value) {
  76671. return;
  76672. }
  76673. this._bloomScale = value;
  76674. // recreate bloom and dispose old as this setting is not dynamic
  76675. this._rebuildBloom();
  76676. this._buildPipeline();
  76677. },
  76678. enumerable: true,
  76679. configurable: true
  76680. });
  76681. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76682. get: function () {
  76683. return this._bloomEnabled;
  76684. },
  76685. /**
  76686. * Enable or disable the bloom from the pipeline
  76687. */
  76688. set: function (enabled) {
  76689. if (this._bloomEnabled === enabled) {
  76690. return;
  76691. }
  76692. this._bloomEnabled = enabled;
  76693. this._buildPipeline();
  76694. },
  76695. enumerable: true,
  76696. configurable: true
  76697. });
  76698. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76699. // recreate bloom and dispose old as this setting is not dynamic
  76700. var oldBloom = this.bloom;
  76701. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76702. this.bloom.threshold = oldBloom.threshold;
  76703. for (var i = 0; i < this._cameras.length; i++) {
  76704. oldBloom.disposeEffects(this._cameras[i]);
  76705. }
  76706. };
  76707. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76708. /**
  76709. * If the depth of field is enabled.
  76710. */
  76711. get: function () {
  76712. return this._depthOfFieldEnabled;
  76713. },
  76714. set: function (enabled) {
  76715. if (this._depthOfFieldEnabled === enabled) {
  76716. return;
  76717. }
  76718. this._depthOfFieldEnabled = enabled;
  76719. this._buildPipeline();
  76720. },
  76721. enumerable: true,
  76722. configurable: true
  76723. });
  76724. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76725. /**
  76726. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76727. */
  76728. get: function () {
  76729. return this._depthOfFieldBlurLevel;
  76730. },
  76731. set: function (value) {
  76732. if (this._depthOfFieldBlurLevel === value) {
  76733. return;
  76734. }
  76735. this._depthOfFieldBlurLevel = value;
  76736. // recreate dof and dispose old as this setting is not dynamic
  76737. var oldDof = this.depthOfField;
  76738. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76739. this.depthOfField.focalLength = oldDof.focalLength;
  76740. this.depthOfField.focusDistance = oldDof.focusDistance;
  76741. this.depthOfField.fStop = oldDof.fStop;
  76742. this.depthOfField.lensSize = oldDof.lensSize;
  76743. for (var i = 0; i < this._cameras.length; i++) {
  76744. oldDof.disposeEffects(this._cameras[i]);
  76745. }
  76746. this._buildPipeline();
  76747. },
  76748. enumerable: true,
  76749. configurable: true
  76750. });
  76751. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76752. get: function () {
  76753. return this._fxaaEnabled;
  76754. },
  76755. /**
  76756. * If the anti aliasing is enabled.
  76757. */
  76758. set: function (enabled) {
  76759. if (this._fxaaEnabled === enabled) {
  76760. return;
  76761. }
  76762. this._fxaaEnabled = enabled;
  76763. this._buildPipeline();
  76764. },
  76765. enumerable: true,
  76766. configurable: true
  76767. });
  76768. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76769. get: function () {
  76770. return this._samples;
  76771. },
  76772. /**
  76773. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76774. */
  76775. set: function (sampleCount) {
  76776. if (this._samples === sampleCount) {
  76777. return;
  76778. }
  76779. this._samples = sampleCount;
  76780. this._buildPipeline();
  76781. },
  76782. enumerable: true,
  76783. configurable: true
  76784. });
  76785. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76786. get: function () {
  76787. return this._imageProcessingEnabled;
  76788. },
  76789. /**
  76790. * If image processing is enabled.
  76791. */
  76792. set: function (enabled) {
  76793. if (this._imageProcessingEnabled === enabled) {
  76794. return;
  76795. }
  76796. this._imageProcessingEnabled = enabled;
  76797. this._buildPipeline();
  76798. },
  76799. enumerable: true,
  76800. configurable: true
  76801. });
  76802. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76803. get: function () {
  76804. return this._glowLayer == null;
  76805. },
  76806. /**
  76807. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76808. */
  76809. set: function (enabled) {
  76810. if (enabled && !this._glowLayer) {
  76811. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76812. }
  76813. else if (!enabled && this._glowLayer) {
  76814. this._glowLayer.dispose();
  76815. this._glowLayer = null;
  76816. }
  76817. },
  76818. enumerable: true,
  76819. configurable: true
  76820. });
  76821. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76822. get: function () {
  76823. return this._chromaticAberrationEnabled;
  76824. },
  76825. /**
  76826. * Enable or disable the chromaticAberration process from the pipeline
  76827. */
  76828. set: function (enabled) {
  76829. if (this._chromaticAberrationEnabled === enabled) {
  76830. return;
  76831. }
  76832. this._chromaticAberrationEnabled = enabled;
  76833. this._buildPipeline();
  76834. },
  76835. enumerable: true,
  76836. configurable: true
  76837. });
  76838. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76839. get: function () {
  76840. return this._grainEnabled;
  76841. },
  76842. /**
  76843. * Enable or disable the grain process from the pipeline
  76844. */
  76845. set: function (enabled) {
  76846. if (this._grainEnabled === enabled) {
  76847. return;
  76848. }
  76849. this._grainEnabled = enabled;
  76850. this._buildPipeline();
  76851. },
  76852. enumerable: true,
  76853. configurable: true
  76854. });
  76855. /**
  76856. * Force the compilation of the entire pipeline.
  76857. */
  76858. DefaultRenderingPipeline.prototype.prepare = function () {
  76859. var previousState = this._buildAllowed;
  76860. this._buildAllowed = true;
  76861. this._buildPipeline();
  76862. this._buildAllowed = previousState;
  76863. };
  76864. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76865. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76866. if (this._hasCleared) {
  76867. postProcess.autoClear = false;
  76868. }
  76869. else {
  76870. postProcess.autoClear = true;
  76871. this._scene.autoClear = false;
  76872. this._hasCleared = true;
  76873. }
  76874. if (!skipTextureSharing) {
  76875. if (this._prevPrevPostProcess) {
  76876. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76877. }
  76878. else {
  76879. postProcess.useOwnOutput();
  76880. }
  76881. if (this._prevPostProcess) {
  76882. this._prevPrevPostProcess = this._prevPostProcess;
  76883. }
  76884. this._prevPostProcess = postProcess;
  76885. }
  76886. };
  76887. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76888. var _this = this;
  76889. if (!this._buildAllowed) {
  76890. return;
  76891. }
  76892. this._scene.autoClear = true;
  76893. var engine = this._scene.getEngine();
  76894. this._disposePostProcesses();
  76895. if (this._cameras !== null) {
  76896. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76897. // get back cameras to be used to reattach pipeline
  76898. this._cameras = this._camerasToBeAttached.slice();
  76899. }
  76900. this._reset();
  76901. this._prevPostProcess = null;
  76902. this._prevPrevPostProcess = null;
  76903. this._hasCleared = false;
  76904. if (this.depthOfFieldEnabled) {
  76905. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76906. this.depthOfField.depthTexture = depthTexture;
  76907. if (!this.depthOfField._isReady()) {
  76908. this.depthOfField._updateEffects();
  76909. }
  76910. this.addEffect(this.depthOfField);
  76911. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76912. }
  76913. if (this.bloomEnabled) {
  76914. if (!this.bloom._isReady()) {
  76915. this.bloom._updateEffects();
  76916. }
  76917. this.addEffect(this.bloom);
  76918. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76919. }
  76920. if (this._imageProcessingEnabled) {
  76921. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76922. if (this._hdr) {
  76923. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76924. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76925. }
  76926. else {
  76927. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76928. }
  76929. }
  76930. if (this.sharpenEnabled) {
  76931. if (!this.sharpen.isReady()) {
  76932. this.sharpen.updateEffect();
  76933. }
  76934. this.addEffect(this._sharpenEffect);
  76935. this._setAutoClearAndTextureSharing(this.sharpen);
  76936. }
  76937. if (this.grainEnabled) {
  76938. if (!this.grain.isReady()) {
  76939. this.grain.updateEffect();
  76940. }
  76941. this.addEffect(this._grainEffect);
  76942. this._setAutoClearAndTextureSharing(this.grain);
  76943. }
  76944. if (this.chromaticAberrationEnabled) {
  76945. if (!this.chromaticAberration.isReady()) {
  76946. this.chromaticAberration.updateEffect();
  76947. }
  76948. this.addEffect(this._chromaticAberrationEffect);
  76949. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76950. }
  76951. if (this.fxaaEnabled) {
  76952. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76953. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76954. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76955. }
  76956. if (this._cameras !== null) {
  76957. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76958. }
  76959. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76960. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76961. }
  76962. };
  76963. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76964. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76965. for (var i = 0; i < this._cameras.length; i++) {
  76966. var camera = this._cameras[i];
  76967. if (this.imageProcessing) {
  76968. this.imageProcessing.dispose(camera);
  76969. }
  76970. if (this.fxaa) {
  76971. this.fxaa.dispose(camera);
  76972. }
  76973. // These are created in the constructor and should not be disposed on every pipeline change
  76974. if (disposeNonRecreated) {
  76975. if (this.sharpen) {
  76976. this.sharpen.dispose(camera);
  76977. }
  76978. if (this.depthOfField) {
  76979. this.depthOfField.disposeEffects(camera);
  76980. }
  76981. if (this.bloom) {
  76982. this.bloom.disposeEffects(camera);
  76983. }
  76984. if (this.chromaticAberration) {
  76985. this.chromaticAberration.dispose(camera);
  76986. }
  76987. if (this.grain) {
  76988. this.grain.dispose(camera);
  76989. }
  76990. if (this._glowLayer) {
  76991. this._glowLayer.dispose();
  76992. }
  76993. }
  76994. }
  76995. this.imageProcessing = null;
  76996. this.fxaa = null;
  76997. if (disposeNonRecreated) {
  76998. this.sharpen = null;
  76999. this._sharpenEffect = null;
  77000. this.depthOfField = null;
  77001. this.bloom = null;
  77002. this.chromaticAberration = null;
  77003. this._chromaticAberrationEffect = null;
  77004. this.grain = null;
  77005. this._grainEffect = null;
  77006. this._glowLayer = null;
  77007. }
  77008. };
  77009. /**
  77010. * Adds a camera to the pipeline
  77011. * @param camera the camera to be added
  77012. */
  77013. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  77014. this._camerasToBeAttached.push(camera);
  77015. this._buildPipeline();
  77016. };
  77017. /**
  77018. * Removes a camera from the pipeline
  77019. * @param camera the camera to remove
  77020. */
  77021. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  77022. var index = this._camerasToBeAttached.indexOf(camera);
  77023. this._camerasToBeAttached.splice(index, 1);
  77024. this._buildPipeline();
  77025. };
  77026. /**
  77027. * Dispose of the pipeline and stop all post processes
  77028. */
  77029. DefaultRenderingPipeline.prototype.dispose = function () {
  77030. this._disposePostProcesses(true);
  77031. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77032. this._scene.autoClear = true;
  77033. if (this._resizeObserver) {
  77034. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  77035. this._resizeObserver = null;
  77036. }
  77037. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  77038. _super.prototype.dispose.call(this);
  77039. };
  77040. /**
  77041. * Serialize the rendering pipeline (Used when exporting)
  77042. * @returns the serialized object
  77043. */
  77044. DefaultRenderingPipeline.prototype.serialize = function () {
  77045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77046. serializationObject.customType = "DefaultRenderingPipeline";
  77047. return serializationObject;
  77048. };
  77049. /**
  77050. * Parse the serialized pipeline
  77051. * @param source Source pipeline.
  77052. * @param scene The scene to load the pipeline to.
  77053. * @param rootUrl The URL of the serialized pipeline.
  77054. * @returns An instantiated pipeline from the serialized object.
  77055. */
  77056. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77057. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  77058. };
  77059. __decorate([
  77060. BABYLON.serialize()
  77061. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  77062. __decorate([
  77063. BABYLON.serialize()
  77064. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  77065. __decorate([
  77066. BABYLON.serialize()
  77067. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  77068. __decorate([
  77069. BABYLON.serialize()
  77070. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  77071. __decorate([
  77072. BABYLON.serialize()
  77073. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  77074. __decorate([
  77075. BABYLON.serialize()
  77076. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  77077. __decorate([
  77078. BABYLON.serialize()
  77079. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  77080. __decorate([
  77081. BABYLON.serialize()
  77082. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  77083. __decorate([
  77084. BABYLON.serialize()
  77085. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  77086. __decorate([
  77087. BABYLON.serialize()
  77088. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  77089. __decorate([
  77090. BABYLON.serialize()
  77091. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  77092. __decorate([
  77093. BABYLON.serialize()
  77094. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  77095. __decorate([
  77096. BABYLON.serialize()
  77097. ], DefaultRenderingPipeline.prototype, "samples", null);
  77098. __decorate([
  77099. BABYLON.serialize()
  77100. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  77101. __decorate([
  77102. BABYLON.serialize()
  77103. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  77104. __decorate([
  77105. BABYLON.serialize()
  77106. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  77107. __decorate([
  77108. BABYLON.serialize()
  77109. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  77110. return DefaultRenderingPipeline;
  77111. }(BABYLON.PostProcessRenderPipeline));
  77112. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  77113. })(BABYLON || (BABYLON = {}));
  77114. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  77115. var BABYLON;
  77116. (function (BABYLON) {
  77117. /**
  77118. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  77119. */
  77120. var GeometryBufferRenderer = /** @class */ (function () {
  77121. /**
  77122. * Creates a new G Buffer for the scene
  77123. * @param scene The scene the buffer belongs to
  77124. * @param ratio How big is the buffer related to the main canvas.
  77125. */
  77126. function GeometryBufferRenderer(scene, ratio) {
  77127. if (ratio === void 0) { ratio = 1; }
  77128. this._enablePosition = false;
  77129. this._scene = scene;
  77130. this._ratio = ratio;
  77131. // Render target
  77132. this._createRenderTargets();
  77133. }
  77134. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  77135. /**
  77136. * Set the render list (meshes to be rendered) used in the G buffer.
  77137. */
  77138. set: function (meshes) {
  77139. this._multiRenderTarget.renderList = meshes;
  77140. },
  77141. enumerable: true,
  77142. configurable: true
  77143. });
  77144. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  77145. /**
  77146. * Gets wether or not G buffer are supported by the running hardware.
  77147. * This requires draw buffer supports
  77148. */
  77149. get: function () {
  77150. return this._multiRenderTarget.isSupported;
  77151. },
  77152. enumerable: true,
  77153. configurable: true
  77154. });
  77155. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  77156. /**
  77157. * Gets wether or not position are enabled for the G buffer.
  77158. */
  77159. get: function () {
  77160. return this._enablePosition;
  77161. },
  77162. /**
  77163. * Sets wether or not position are enabled for the G buffer.
  77164. */
  77165. set: function (enable) {
  77166. this._enablePosition = enable;
  77167. this.dispose();
  77168. this._createRenderTargets();
  77169. },
  77170. enumerable: true,
  77171. configurable: true
  77172. });
  77173. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  77174. /**
  77175. * Gets the scene associated with the buffer.
  77176. */
  77177. get: function () {
  77178. return this._scene;
  77179. },
  77180. enumerable: true,
  77181. configurable: true
  77182. });
  77183. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  77184. /**
  77185. * Gets the ratio used by the buffer during its creation.
  77186. * How big is the buffer related to the main canvas.
  77187. */
  77188. get: function () {
  77189. return this._ratio;
  77190. },
  77191. enumerable: true,
  77192. configurable: true
  77193. });
  77194. /**
  77195. * Checks wether everything is ready to render a submesh to the G buffer.
  77196. * @param subMesh the submesh to check readiness for
  77197. * @param useInstances is the mesh drawn using instance or not
  77198. * @returns true if ready otherwise false
  77199. */
  77200. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  77201. var material = subMesh.getMaterial();
  77202. if (material && material.disableDepthWrite) {
  77203. return false;
  77204. }
  77205. var defines = [];
  77206. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  77207. var mesh = subMesh.getMesh();
  77208. // Alpha test
  77209. if (material && material.needAlphaTesting()) {
  77210. defines.push("#define ALPHATEST");
  77211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77212. attribs.push(BABYLON.VertexBuffer.UVKind);
  77213. defines.push("#define UV1");
  77214. }
  77215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  77216. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77217. defines.push("#define UV2");
  77218. }
  77219. }
  77220. // Buffers
  77221. if (this._enablePosition) {
  77222. defines.push("#define POSITION");
  77223. }
  77224. // Bones
  77225. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77226. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77227. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77228. if (mesh.numBoneInfluencers > 4) {
  77229. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77230. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77231. }
  77232. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77233. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77234. }
  77235. else {
  77236. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77237. }
  77238. // Instances
  77239. if (useInstances) {
  77240. defines.push("#define INSTANCES");
  77241. attribs.push("world0");
  77242. attribs.push("world1");
  77243. attribs.push("world2");
  77244. attribs.push("world3");
  77245. }
  77246. // Get correct effect
  77247. var join = defines.join("\n");
  77248. if (this._cachedDefines !== join) {
  77249. this._cachedDefines = join;
  77250. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77251. }
  77252. return this._effect.isReady();
  77253. };
  77254. /**
  77255. * Gets the current underlying G Buffer.
  77256. * @returns the buffer
  77257. */
  77258. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77259. return this._multiRenderTarget;
  77260. };
  77261. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77262. /**
  77263. * Gets the number of samples used to render the buffer (anti aliasing).
  77264. */
  77265. get: function () {
  77266. return this._multiRenderTarget.samples;
  77267. },
  77268. /**
  77269. * Sets the number of samples used to render the buffer (anti aliasing).
  77270. */
  77271. set: function (value) {
  77272. this._multiRenderTarget.samples = value;
  77273. },
  77274. enumerable: true,
  77275. configurable: true
  77276. });
  77277. /**
  77278. * Disposes the renderer and frees up associated resources.
  77279. */
  77280. GeometryBufferRenderer.prototype.dispose = function () {
  77281. this.getGBuffer().dispose();
  77282. };
  77283. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77284. var _this = this;
  77285. var engine = this._scene.getEngine();
  77286. var count = this._enablePosition ? 3 : 2;
  77287. 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 });
  77288. if (!this.isSupported) {
  77289. return;
  77290. }
  77291. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77292. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77293. this._multiRenderTarget.refreshRate = 1;
  77294. this._multiRenderTarget.renderParticles = false;
  77295. this._multiRenderTarget.renderList = null;
  77296. // set default depth value to 1.0 (far away)
  77297. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77298. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77299. });
  77300. // Custom render function
  77301. var renderSubMesh = function (subMesh) {
  77302. var mesh = subMesh.getRenderingMesh();
  77303. var scene = _this._scene;
  77304. var engine = scene.getEngine();
  77305. var material = subMesh.getMaterial();
  77306. if (!material) {
  77307. return;
  77308. }
  77309. // Culling
  77310. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77311. // Managing instances
  77312. var batch = mesh._getInstancesRenderList(subMesh._id);
  77313. if (batch.mustReturn) {
  77314. return;
  77315. }
  77316. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77317. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77318. engine.enableEffect(_this._effect);
  77319. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77320. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77321. _this._effect.setMatrix("view", scene.getViewMatrix());
  77322. // Alpha test
  77323. if (material && material.needAlphaTesting()) {
  77324. var alphaTexture = material.getAlphaTestTexture();
  77325. if (alphaTexture) {
  77326. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77327. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77328. }
  77329. }
  77330. // Bones
  77331. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77332. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77333. }
  77334. // Draw
  77335. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77336. }
  77337. };
  77338. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77339. var index;
  77340. if (depthOnlySubMeshes.length) {
  77341. engine.setColorWrite(false);
  77342. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77343. renderSubMesh(depthOnlySubMeshes.data[index]);
  77344. }
  77345. engine.setColorWrite(true);
  77346. }
  77347. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77348. renderSubMesh(opaqueSubMeshes.data[index]);
  77349. }
  77350. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77351. renderSubMesh(alphaTestSubMeshes.data[index]);
  77352. }
  77353. };
  77354. };
  77355. return GeometryBufferRenderer;
  77356. }());
  77357. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77358. })(BABYLON || (BABYLON = {}));
  77359. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77360. var BABYLON;
  77361. (function (BABYLON) {
  77362. /**
  77363. * This groups together the common properties used for image processing either in direct forward pass
  77364. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77365. * or not.
  77366. */
  77367. var ImageProcessingConfiguration = /** @class */ (function () {
  77368. function ImageProcessingConfiguration() {
  77369. /**
  77370. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77371. */
  77372. this.colorCurves = new BABYLON.ColorCurves();
  77373. this._colorCurvesEnabled = false;
  77374. this._colorGradingEnabled = false;
  77375. this._colorGradingWithGreenDepth = true;
  77376. this._colorGradingBGR = true;
  77377. this._exposure = 1.0;
  77378. this._toneMappingEnabled = false;
  77379. this._contrast = 1.0;
  77380. /**
  77381. * Vignette stretch size.
  77382. */
  77383. this.vignetteStretch = 0;
  77384. /**
  77385. * Vignette centre X Offset.
  77386. */
  77387. this.vignetteCentreX = 0;
  77388. /**
  77389. * Vignette centre Y Offset.
  77390. */
  77391. this.vignetteCentreY = 0;
  77392. /**
  77393. * Vignette weight or intensity of the vignette effect.
  77394. */
  77395. this.vignetteWeight = 1.5;
  77396. /**
  77397. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77398. * if vignetteEnabled is set to true.
  77399. */
  77400. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77401. /**
  77402. * Camera field of view used by the Vignette effect.
  77403. */
  77404. this.vignetteCameraFov = 0.5;
  77405. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77406. this._vignetteEnabled = false;
  77407. this._applyByPostProcess = false;
  77408. this._isEnabled = true;
  77409. /**
  77410. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77411. */
  77412. this.onUpdateParameters = new BABYLON.Observable();
  77413. }
  77414. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77415. /**
  77416. * Gets wether the color curves effect is enabled.
  77417. */
  77418. get: function () {
  77419. return this._colorCurvesEnabled;
  77420. },
  77421. /**
  77422. * Sets wether the color curves effect is enabled.
  77423. */
  77424. set: function (value) {
  77425. if (this._colorCurvesEnabled === value) {
  77426. return;
  77427. }
  77428. this._colorCurvesEnabled = value;
  77429. this._updateParameters();
  77430. },
  77431. enumerable: true,
  77432. configurable: true
  77433. });
  77434. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77435. /**
  77436. * Gets wether the color grading effect is enabled.
  77437. */
  77438. get: function () {
  77439. return this._colorGradingEnabled;
  77440. },
  77441. /**
  77442. * Sets wether the color grading effect is enabled.
  77443. */
  77444. set: function (value) {
  77445. if (this._colorGradingEnabled === value) {
  77446. return;
  77447. }
  77448. this._colorGradingEnabled = value;
  77449. this._updateParameters();
  77450. },
  77451. enumerable: true,
  77452. configurable: true
  77453. });
  77454. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77455. /**
  77456. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77457. */
  77458. get: function () {
  77459. return this._colorGradingWithGreenDepth;
  77460. },
  77461. /**
  77462. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77463. */
  77464. set: function (value) {
  77465. if (this._colorGradingWithGreenDepth === value) {
  77466. return;
  77467. }
  77468. this._colorGradingWithGreenDepth = value;
  77469. this._updateParameters();
  77470. },
  77471. enumerable: true,
  77472. configurable: true
  77473. });
  77474. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77475. /**
  77476. * Gets wether the color grading texture contains BGR values.
  77477. */
  77478. get: function () {
  77479. return this._colorGradingBGR;
  77480. },
  77481. /**
  77482. * Sets wether the color grading texture contains BGR values.
  77483. */
  77484. set: function (value) {
  77485. if (this._colorGradingBGR === value) {
  77486. return;
  77487. }
  77488. this._colorGradingBGR = value;
  77489. this._updateParameters();
  77490. },
  77491. enumerable: true,
  77492. configurable: true
  77493. });
  77494. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77495. /**
  77496. * Gets the Exposure used in the effect.
  77497. */
  77498. get: function () {
  77499. return this._exposure;
  77500. },
  77501. /**
  77502. * Sets the Exposure used in the effect.
  77503. */
  77504. set: function (value) {
  77505. if (this._exposure === value) {
  77506. return;
  77507. }
  77508. this._exposure = value;
  77509. this._updateParameters();
  77510. },
  77511. enumerable: true,
  77512. configurable: true
  77513. });
  77514. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77515. /**
  77516. * Gets wether the tone mapping effect is enabled.
  77517. */
  77518. get: function () {
  77519. return this._toneMappingEnabled;
  77520. },
  77521. /**
  77522. * Sets wether the tone mapping effect is enabled.
  77523. */
  77524. set: function (value) {
  77525. if (this._toneMappingEnabled === value) {
  77526. return;
  77527. }
  77528. this._toneMappingEnabled = value;
  77529. this._updateParameters();
  77530. },
  77531. enumerable: true,
  77532. configurable: true
  77533. });
  77534. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77535. /**
  77536. * Gets the contrast used in the effect.
  77537. */
  77538. get: function () {
  77539. return this._contrast;
  77540. },
  77541. /**
  77542. * Sets the contrast used in the effect.
  77543. */
  77544. set: function (value) {
  77545. if (this._contrast === value) {
  77546. return;
  77547. }
  77548. this._contrast = value;
  77549. this._updateParameters();
  77550. },
  77551. enumerable: true,
  77552. configurable: true
  77553. });
  77554. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77555. /**
  77556. * Gets the vignette blend mode allowing different kind of effect.
  77557. */
  77558. get: function () {
  77559. return this._vignetteBlendMode;
  77560. },
  77561. /**
  77562. * Sets the vignette blend mode allowing different kind of effect.
  77563. */
  77564. set: function (value) {
  77565. if (this._vignetteBlendMode === value) {
  77566. return;
  77567. }
  77568. this._vignetteBlendMode = value;
  77569. this._updateParameters();
  77570. },
  77571. enumerable: true,
  77572. configurable: true
  77573. });
  77574. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77575. /**
  77576. * Gets wether the vignette effect is enabled.
  77577. */
  77578. get: function () {
  77579. return this._vignetteEnabled;
  77580. },
  77581. /**
  77582. * Sets wether the vignette effect is enabled.
  77583. */
  77584. set: function (value) {
  77585. if (this._vignetteEnabled === value) {
  77586. return;
  77587. }
  77588. this._vignetteEnabled = value;
  77589. this._updateParameters();
  77590. },
  77591. enumerable: true,
  77592. configurable: true
  77593. });
  77594. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77595. /**
  77596. * Gets wether the image processing is applied through a post process or not.
  77597. */
  77598. get: function () {
  77599. return this._applyByPostProcess;
  77600. },
  77601. /**
  77602. * Sets wether the image processing is applied through a post process or not.
  77603. */
  77604. set: function (value) {
  77605. if (this._applyByPostProcess === value) {
  77606. return;
  77607. }
  77608. this._applyByPostProcess = value;
  77609. this._updateParameters();
  77610. },
  77611. enumerable: true,
  77612. configurable: true
  77613. });
  77614. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77615. /**
  77616. * Gets wether the image processing is enabled or not.
  77617. */
  77618. get: function () {
  77619. return this._isEnabled;
  77620. },
  77621. /**
  77622. * Sets wether the image processing is enabled or not.
  77623. */
  77624. set: function (value) {
  77625. if (this._isEnabled === value) {
  77626. return;
  77627. }
  77628. this._isEnabled = value;
  77629. this._updateParameters();
  77630. },
  77631. enumerable: true,
  77632. configurable: true
  77633. });
  77634. /**
  77635. * Method called each time the image processing information changes requires to recompile the effect.
  77636. */
  77637. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77638. this.onUpdateParameters.notifyObservers(this);
  77639. };
  77640. ImageProcessingConfiguration.prototype.getClassName = function () {
  77641. return "ImageProcessingConfiguration";
  77642. };
  77643. /**
  77644. * Prepare the list of uniforms associated with the Image Processing effects.
  77645. * @param uniformsList The list of uniforms used in the effect
  77646. * @param defines the list of defines currently in use
  77647. */
  77648. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77649. if (defines.EXPOSURE) {
  77650. uniforms.push("exposureLinear");
  77651. }
  77652. if (defines.CONTRAST) {
  77653. uniforms.push("contrast");
  77654. }
  77655. if (defines.COLORGRADING) {
  77656. uniforms.push("colorTransformSettings");
  77657. }
  77658. if (defines.VIGNETTE) {
  77659. uniforms.push("vInverseScreenSize");
  77660. uniforms.push("vignetteSettings1");
  77661. uniforms.push("vignetteSettings2");
  77662. }
  77663. if (defines.COLORCURVES) {
  77664. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77665. }
  77666. };
  77667. /**
  77668. * Prepare the list of samplers associated with the Image Processing effects.
  77669. * @param uniformsList The list of uniforms used in the effect
  77670. * @param defines the list of defines currently in use
  77671. */
  77672. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77673. if (defines.COLORGRADING) {
  77674. samplersList.push("txColorTransform");
  77675. }
  77676. };
  77677. /**
  77678. * Prepare the list of defines associated to the shader.
  77679. * @param defines the list of defines to complete
  77680. */
  77681. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77682. if (forPostProcess === void 0) { forPostProcess = false; }
  77683. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77684. defines.VIGNETTE = false;
  77685. defines.TONEMAPPING = false;
  77686. defines.CONTRAST = false;
  77687. defines.EXPOSURE = false;
  77688. defines.COLORCURVES = false;
  77689. defines.COLORGRADING = false;
  77690. defines.COLORGRADING3D = false;
  77691. defines.IMAGEPROCESSING = false;
  77692. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77693. return;
  77694. }
  77695. defines.VIGNETTE = this.vignetteEnabled;
  77696. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77697. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77698. defines.TONEMAPPING = this.toneMappingEnabled;
  77699. defines.CONTRAST = (this.contrast !== 1.0);
  77700. defines.EXPOSURE = (this.exposure !== 1.0);
  77701. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77702. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77703. if (defines.COLORGRADING) {
  77704. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77705. }
  77706. else {
  77707. defines.COLORGRADING3D = false;
  77708. }
  77709. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77710. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77711. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77712. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77713. };
  77714. /**
  77715. * Returns true if all the image processing information are ready.
  77716. */
  77717. ImageProcessingConfiguration.prototype.isReady = function () {
  77718. // Color Grading texure can not be none blocking.
  77719. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77720. };
  77721. /**
  77722. * Binds the image processing to the shader.
  77723. * @param effect The effect to bind to
  77724. */
  77725. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77726. if (aspectRatio === void 0) { aspectRatio = 1; }
  77727. // Color Curves
  77728. if (this._colorCurvesEnabled && this.colorCurves) {
  77729. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77730. }
  77731. // Vignette
  77732. if (this._vignetteEnabled) {
  77733. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77734. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77735. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77736. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77737. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77738. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77739. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77740. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77741. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77742. var vignettePower = -2.0 * this.vignetteWeight;
  77743. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77744. }
  77745. // Exposure
  77746. effect.setFloat("exposureLinear", this.exposure);
  77747. // Contrast
  77748. effect.setFloat("contrast", this.contrast);
  77749. // Color transform settings
  77750. if (this.colorGradingTexture) {
  77751. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77752. var textureSize = this.colorGradingTexture.getSize().height;
  77753. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77754. 0.5 / textureSize, // textureOffset
  77755. textureSize, // textureSize
  77756. this.colorGradingTexture.level // weight
  77757. );
  77758. }
  77759. };
  77760. /**
  77761. * Clones the current image processing instance.
  77762. * @return The cloned image processing
  77763. */
  77764. ImageProcessingConfiguration.prototype.clone = function () {
  77765. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77766. };
  77767. /**
  77768. * Serializes the current image processing instance to a json representation.
  77769. * @return a JSON representation
  77770. */
  77771. ImageProcessingConfiguration.prototype.serialize = function () {
  77772. return BABYLON.SerializationHelper.Serialize(this);
  77773. };
  77774. /**
  77775. * Parses the image processing from a json representation.
  77776. * @param source the JSON source to parse
  77777. * @return The parsed image processing
  77778. */
  77779. ImageProcessingConfiguration.Parse = function (source) {
  77780. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77781. };
  77782. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77783. /**
  77784. * Used to apply the vignette as a mix with the pixel color.
  77785. */
  77786. get: function () {
  77787. return this._VIGNETTEMODE_MULTIPLY;
  77788. },
  77789. enumerable: true,
  77790. configurable: true
  77791. });
  77792. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77793. /**
  77794. * Used to apply the vignette as a replacement of the pixel color.
  77795. */
  77796. get: function () {
  77797. return this._VIGNETTEMODE_OPAQUE;
  77798. },
  77799. enumerable: true,
  77800. configurable: true
  77801. });
  77802. // Static constants associated to the image processing.
  77803. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77804. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77805. __decorate([
  77806. BABYLON.serializeAsColorCurves()
  77807. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77808. __decorate([
  77809. BABYLON.serialize()
  77810. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77811. __decorate([
  77812. BABYLON.serializeAsTexture()
  77813. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77814. __decorate([
  77815. BABYLON.serialize()
  77816. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77817. __decorate([
  77818. BABYLON.serialize()
  77819. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77820. __decorate([
  77821. BABYLON.serialize()
  77822. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77823. __decorate([
  77824. BABYLON.serialize()
  77825. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77826. __decorate([
  77827. BABYLON.serialize()
  77828. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77829. __decorate([
  77830. BABYLON.serialize()
  77831. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77832. __decorate([
  77833. BABYLON.serialize()
  77834. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77835. __decorate([
  77836. BABYLON.serialize()
  77837. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77838. __decorate([
  77839. BABYLON.serialize()
  77840. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77841. __decorate([
  77842. BABYLON.serialize()
  77843. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77844. __decorate([
  77845. BABYLON.serializeAsColor4()
  77846. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77847. __decorate([
  77848. BABYLON.serialize()
  77849. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77850. __decorate([
  77851. BABYLON.serialize()
  77852. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77853. __decorate([
  77854. BABYLON.serialize()
  77855. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77856. __decorate([
  77857. BABYLON.serialize()
  77858. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77859. __decorate([
  77860. BABYLON.serialize()
  77861. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77862. return ImageProcessingConfiguration;
  77863. }());
  77864. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77865. })(BABYLON || (BABYLON = {}));
  77866. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77867. var BABYLON;
  77868. (function (BABYLON) {
  77869. /**
  77870. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77871. * It can help converting any input color in a desired output one. This can then be used to create effects
  77872. * from sepia, black and white to sixties or futuristic rendering...
  77873. *
  77874. * The only supported format is currently 3dl.
  77875. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77876. */
  77877. var ColorGradingTexture = /** @class */ (function (_super) {
  77878. __extends(ColorGradingTexture, _super);
  77879. /**
  77880. * Instantiates a ColorGradingTexture from the following parameters.
  77881. *
  77882. * @param url The location of the color gradind data (currently only supporting 3dl)
  77883. * @param scene The scene the texture will be used in
  77884. */
  77885. function ColorGradingTexture(url, scene) {
  77886. var _this = _super.call(this, scene) || this;
  77887. if (!url) {
  77888. return _this;
  77889. }
  77890. _this._engine = scene.getEngine();
  77891. _this._textureMatrix = BABYLON.Matrix.Identity();
  77892. _this.name = url;
  77893. _this.url = url;
  77894. _this.hasAlpha = false;
  77895. _this.isCube = false;
  77896. _this.is3D = _this._engine.webGLVersion > 1;
  77897. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77898. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77899. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77900. _this.anisotropicFilteringLevel = 1;
  77901. _this._texture = _this._getFromCache(url, true);
  77902. if (!_this._texture) {
  77903. if (!scene.useDelayedTextureLoading) {
  77904. _this.loadTexture();
  77905. }
  77906. else {
  77907. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77908. }
  77909. }
  77910. return _this;
  77911. }
  77912. /**
  77913. * Returns the texture matrix used in most of the material.
  77914. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77915. */
  77916. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77917. return this._textureMatrix;
  77918. };
  77919. /**
  77920. * Occurs when the file being loaded is a .3dl LUT file.
  77921. */
  77922. ColorGradingTexture.prototype.load3dlTexture = function () {
  77923. var engine = this._engine;
  77924. var texture;
  77925. if (engine.webGLVersion === 1) {
  77926. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77927. }
  77928. else {
  77929. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77930. }
  77931. this._texture = texture;
  77932. var callback = function (text) {
  77933. if (typeof text !== "string") {
  77934. return;
  77935. }
  77936. var data = null;
  77937. var tempData = null;
  77938. var line;
  77939. var lines = text.split('\n');
  77940. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77941. var maxColor = 0;
  77942. for (var i = 0; i < lines.length; i++) {
  77943. line = lines[i];
  77944. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77945. continue;
  77946. if (line.indexOf('#') === 0)
  77947. continue;
  77948. var words = line.split(" ");
  77949. if (size === 0) {
  77950. // Number of space + one
  77951. size = words.length;
  77952. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77953. tempData = new Float32Array(size * size * size * 4);
  77954. continue;
  77955. }
  77956. if (size != 0) {
  77957. var r = Math.max(parseInt(words[0]), 0);
  77958. var g = Math.max(parseInt(words[1]), 0);
  77959. var b = Math.max(parseInt(words[2]), 0);
  77960. maxColor = Math.max(r, maxColor);
  77961. maxColor = Math.max(g, maxColor);
  77962. maxColor = Math.max(b, maxColor);
  77963. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77964. if (tempData) {
  77965. tempData[pixelStorageIndex + 0] = r;
  77966. tempData[pixelStorageIndex + 1] = g;
  77967. tempData[pixelStorageIndex + 2] = b;
  77968. }
  77969. pixelIndexSlice++;
  77970. if (pixelIndexSlice % size == 0) {
  77971. pixelIndexH++;
  77972. pixelIndexSlice = 0;
  77973. if (pixelIndexH % size == 0) {
  77974. pixelIndexW++;
  77975. pixelIndexH = 0;
  77976. }
  77977. }
  77978. }
  77979. }
  77980. if (tempData && data) {
  77981. for (var i = 0; i < tempData.length; i++) {
  77982. if (i > 0 && (i + 1) % 4 === 0) {
  77983. data[i] = 255;
  77984. }
  77985. else {
  77986. var value = tempData[i];
  77987. data[i] = (value / maxColor * 255);
  77988. }
  77989. }
  77990. }
  77991. if (texture.is3D) {
  77992. texture.updateSize(size, size, size);
  77993. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77994. }
  77995. else {
  77996. texture.updateSize(size * size, size);
  77997. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77998. }
  77999. };
  78000. var scene = this.getScene();
  78001. if (scene) {
  78002. scene._loadFile(this.url, callback);
  78003. }
  78004. else {
  78005. this._engine._loadFile(this.url, callback);
  78006. }
  78007. return this._texture;
  78008. };
  78009. /**
  78010. * Starts the loading process of the texture.
  78011. */
  78012. ColorGradingTexture.prototype.loadTexture = function () {
  78013. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  78014. this.load3dlTexture();
  78015. }
  78016. };
  78017. /**
  78018. * Clones the color gradind texture.
  78019. */
  78020. ColorGradingTexture.prototype.clone = function () {
  78021. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  78022. // Base texture
  78023. newTexture.level = this.level;
  78024. return newTexture;
  78025. };
  78026. /**
  78027. * Called during delayed load for textures.
  78028. */
  78029. ColorGradingTexture.prototype.delayLoad = function () {
  78030. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  78031. return;
  78032. }
  78033. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  78034. this._texture = this._getFromCache(this.url, true);
  78035. if (!this._texture) {
  78036. this.loadTexture();
  78037. }
  78038. };
  78039. /**
  78040. * Parses a color grading texture serialized by Babylon.
  78041. * @param parsedTexture The texture information being parsedTexture
  78042. * @param scene The scene to load the texture in
  78043. * @param rootUrl The root url of the data assets to load
  78044. * @return A color gradind texture
  78045. */
  78046. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  78047. var texture = null;
  78048. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  78049. texture = new ColorGradingTexture(parsedTexture.name, scene);
  78050. texture.name = parsedTexture.name;
  78051. texture.level = parsedTexture.level;
  78052. }
  78053. return texture;
  78054. };
  78055. /**
  78056. * Serializes the LUT texture to json format.
  78057. */
  78058. ColorGradingTexture.prototype.serialize = function () {
  78059. if (!this.name) {
  78060. return null;
  78061. }
  78062. var serializationObject = {};
  78063. serializationObject.name = this.name;
  78064. serializationObject.level = this.level;
  78065. serializationObject.customType = "BABYLON.ColorGradingTexture";
  78066. return serializationObject;
  78067. };
  78068. /**
  78069. * Empty line regex stored for GC.
  78070. */
  78071. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  78072. return ColorGradingTexture;
  78073. }(BABYLON.BaseTexture));
  78074. BABYLON.ColorGradingTexture = ColorGradingTexture;
  78075. })(BABYLON || (BABYLON = {}));
  78076. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  78077. var BABYLON;
  78078. (function (BABYLON) {
  78079. /**
  78080. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  78081. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  78082. * 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;
  78083. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  78084. */
  78085. var ColorCurves = /** @class */ (function () {
  78086. function ColorCurves() {
  78087. this._dirty = true;
  78088. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  78089. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  78090. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78091. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  78092. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  78093. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  78094. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  78095. this._globalHue = 30;
  78096. this._globalDensity = 0;
  78097. this._globalSaturation = 0;
  78098. this._globalExposure = 0;
  78099. this._highlightsHue = 30;
  78100. this._highlightsDensity = 0;
  78101. this._highlightsSaturation = 0;
  78102. this._highlightsExposure = 0;
  78103. this._midtonesHue = 30;
  78104. this._midtonesDensity = 0;
  78105. this._midtonesSaturation = 0;
  78106. this._midtonesExposure = 0;
  78107. this._shadowsHue = 30;
  78108. this._shadowsDensity = 0;
  78109. this._shadowsSaturation = 0;
  78110. this._shadowsExposure = 0;
  78111. }
  78112. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  78113. /**
  78114. * Gets the global Hue value.
  78115. * 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).
  78116. */
  78117. get: function () {
  78118. return this._globalHue;
  78119. },
  78120. /**
  78121. * Sets the global Hue value.
  78122. * 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).
  78123. */
  78124. set: function (value) {
  78125. this._globalHue = value;
  78126. this._dirty = true;
  78127. },
  78128. enumerable: true,
  78129. configurable: true
  78130. });
  78131. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  78132. /**
  78133. * Gets the global Density value.
  78134. * 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.
  78135. * Values less than zero provide a filter of opposite hue.
  78136. */
  78137. get: function () {
  78138. return this._globalDensity;
  78139. },
  78140. /**
  78141. * Sets the global Density value.
  78142. * 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.
  78143. * Values less than zero provide a filter of opposite hue.
  78144. */
  78145. set: function (value) {
  78146. this._globalDensity = value;
  78147. this._dirty = true;
  78148. },
  78149. enumerable: true,
  78150. configurable: true
  78151. });
  78152. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  78153. /**
  78154. * Gets the global Saturation value.
  78155. * 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.
  78156. */
  78157. get: function () {
  78158. return this._globalSaturation;
  78159. },
  78160. /**
  78161. * Sets the global Saturation value.
  78162. * 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.
  78163. */
  78164. set: function (value) {
  78165. this._globalSaturation = value;
  78166. this._dirty = true;
  78167. },
  78168. enumerable: true,
  78169. configurable: true
  78170. });
  78171. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  78172. /**
  78173. * Gets the global Exposure value.
  78174. * 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.
  78175. */
  78176. get: function () {
  78177. return this._globalExposure;
  78178. },
  78179. /**
  78180. * Sets the global Exposure value.
  78181. * 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.
  78182. */
  78183. set: function (value) {
  78184. this._globalExposure = value;
  78185. this._dirty = true;
  78186. },
  78187. enumerable: true,
  78188. configurable: true
  78189. });
  78190. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  78191. /**
  78192. * Gets the highlights Hue value.
  78193. * 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).
  78194. */
  78195. get: function () {
  78196. return this._highlightsHue;
  78197. },
  78198. /**
  78199. * Sets the highlights Hue value.
  78200. * 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).
  78201. */
  78202. set: function (value) {
  78203. this._highlightsHue = value;
  78204. this._dirty = true;
  78205. },
  78206. enumerable: true,
  78207. configurable: true
  78208. });
  78209. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  78210. /**
  78211. * Gets the highlights Density value.
  78212. * 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.
  78213. * Values less than zero provide a filter of opposite hue.
  78214. */
  78215. get: function () {
  78216. return this._highlightsDensity;
  78217. },
  78218. /**
  78219. * Sets the highlights Density value.
  78220. * 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.
  78221. * Values less than zero provide a filter of opposite hue.
  78222. */
  78223. set: function (value) {
  78224. this._highlightsDensity = value;
  78225. this._dirty = true;
  78226. },
  78227. enumerable: true,
  78228. configurable: true
  78229. });
  78230. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  78231. /**
  78232. * Gets the highlights Saturation value.
  78233. * 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.
  78234. */
  78235. get: function () {
  78236. return this._highlightsSaturation;
  78237. },
  78238. /**
  78239. * Sets the highlights Saturation value.
  78240. * 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.
  78241. */
  78242. set: function (value) {
  78243. this._highlightsSaturation = value;
  78244. this._dirty = true;
  78245. },
  78246. enumerable: true,
  78247. configurable: true
  78248. });
  78249. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78250. /**
  78251. * Gets the highlights Exposure value.
  78252. * 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.
  78253. */
  78254. get: function () {
  78255. return this._highlightsExposure;
  78256. },
  78257. /**
  78258. * Sets the highlights Exposure value.
  78259. * 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.
  78260. */
  78261. set: function (value) {
  78262. this._highlightsExposure = value;
  78263. this._dirty = true;
  78264. },
  78265. enumerable: true,
  78266. configurable: true
  78267. });
  78268. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78269. /**
  78270. * Gets the midtones Hue value.
  78271. * 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).
  78272. */
  78273. get: function () {
  78274. return this._midtonesHue;
  78275. },
  78276. /**
  78277. * Sets the midtones Hue value.
  78278. * 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).
  78279. */
  78280. set: function (value) {
  78281. this._midtonesHue = value;
  78282. this._dirty = true;
  78283. },
  78284. enumerable: true,
  78285. configurable: true
  78286. });
  78287. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78288. /**
  78289. * Gets the midtones Density value.
  78290. * 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.
  78291. * Values less than zero provide a filter of opposite hue.
  78292. */
  78293. get: function () {
  78294. return this._midtonesDensity;
  78295. },
  78296. /**
  78297. * Sets the midtones Density value.
  78298. * 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.
  78299. * Values less than zero provide a filter of opposite hue.
  78300. */
  78301. set: function (value) {
  78302. this._midtonesDensity = value;
  78303. this._dirty = true;
  78304. },
  78305. enumerable: true,
  78306. configurable: true
  78307. });
  78308. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78309. /**
  78310. * Gets the midtones Saturation value.
  78311. * 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.
  78312. */
  78313. get: function () {
  78314. return this._midtonesSaturation;
  78315. },
  78316. /**
  78317. * Sets the midtones Saturation value.
  78318. * 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.
  78319. */
  78320. set: function (value) {
  78321. this._midtonesSaturation = value;
  78322. this._dirty = true;
  78323. },
  78324. enumerable: true,
  78325. configurable: true
  78326. });
  78327. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78328. /**
  78329. * Gets the midtones Exposure value.
  78330. * 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.
  78331. */
  78332. get: function () {
  78333. return this._midtonesExposure;
  78334. },
  78335. /**
  78336. * Sets the midtones Exposure value.
  78337. * 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.
  78338. */
  78339. set: function (value) {
  78340. this._midtonesExposure = value;
  78341. this._dirty = true;
  78342. },
  78343. enumerable: true,
  78344. configurable: true
  78345. });
  78346. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78347. /**
  78348. * Gets the shadows Hue value.
  78349. * 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).
  78350. */
  78351. get: function () {
  78352. return this._shadowsHue;
  78353. },
  78354. /**
  78355. * Sets the shadows Hue value.
  78356. * 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).
  78357. */
  78358. set: function (value) {
  78359. this._shadowsHue = value;
  78360. this._dirty = true;
  78361. },
  78362. enumerable: true,
  78363. configurable: true
  78364. });
  78365. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78366. /**
  78367. * Gets the shadows Density value.
  78368. * 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.
  78369. * Values less than zero provide a filter of opposite hue.
  78370. */
  78371. get: function () {
  78372. return this._shadowsDensity;
  78373. },
  78374. /**
  78375. * Sets the shadows Density value.
  78376. * 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.
  78377. * Values less than zero provide a filter of opposite hue.
  78378. */
  78379. set: function (value) {
  78380. this._shadowsDensity = value;
  78381. this._dirty = true;
  78382. },
  78383. enumerable: true,
  78384. configurable: true
  78385. });
  78386. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78387. /**
  78388. * Gets the shadows Saturation value.
  78389. * 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.
  78390. */
  78391. get: function () {
  78392. return this._shadowsSaturation;
  78393. },
  78394. /**
  78395. * Sets the shadows Saturation value.
  78396. * 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.
  78397. */
  78398. set: function (value) {
  78399. this._shadowsSaturation = value;
  78400. this._dirty = true;
  78401. },
  78402. enumerable: true,
  78403. configurable: true
  78404. });
  78405. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78406. /**
  78407. * Gets the shadows Exposure value.
  78408. * 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.
  78409. */
  78410. get: function () {
  78411. return this._shadowsExposure;
  78412. },
  78413. /**
  78414. * Sets the shadows Exposure value.
  78415. * 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.
  78416. */
  78417. set: function (value) {
  78418. this._shadowsExposure = value;
  78419. this._dirty = true;
  78420. },
  78421. enumerable: true,
  78422. configurable: true
  78423. });
  78424. ColorCurves.prototype.getClassName = function () {
  78425. return "ColorCurves";
  78426. };
  78427. /**
  78428. * Binds the color curves to the shader.
  78429. * @param colorCurves The color curve to bind
  78430. * @param effect The effect to bind to
  78431. */
  78432. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78433. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78434. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78435. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78436. if (colorCurves._dirty) {
  78437. colorCurves._dirty = false;
  78438. // Fill in global info.
  78439. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78440. // Compute highlights info.
  78441. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78442. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78443. // Compute midtones info.
  78444. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78445. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78446. // Compute shadows info.
  78447. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78448. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78449. // Compute deltas (neutral is midtones).
  78450. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78451. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78452. }
  78453. if (effect) {
  78454. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78455. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78456. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78457. }
  78458. };
  78459. /**
  78460. * Prepare the list of uniforms associated with the ColorCurves effects.
  78461. * @param uniformsList The list of uniforms used in the effect
  78462. */
  78463. ColorCurves.PrepareUniforms = function (uniformsList) {
  78464. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78465. };
  78466. /**
  78467. * Returns color grading data based on a hue, density, saturation and exposure value.
  78468. * @param filterHue The hue of the color filter.
  78469. * @param filterDensity The density of the color filter.
  78470. * @param saturation The saturation.
  78471. * @param exposure The exposure.
  78472. * @param result The result data container.
  78473. */
  78474. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78475. if (hue == null) {
  78476. return;
  78477. }
  78478. hue = ColorCurves.clamp(hue, 0, 360);
  78479. density = ColorCurves.clamp(density, -100, 100);
  78480. saturation = ColorCurves.clamp(saturation, -100, 100);
  78481. exposure = ColorCurves.clamp(exposure, -100, 100);
  78482. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78483. // so that the maximum filter density is only 50% control. This provides fine control
  78484. // for small values and reasonable range.
  78485. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78486. density *= 0.5;
  78487. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78488. if (density < 0) {
  78489. density *= -1;
  78490. hue = (hue + 180) % 360;
  78491. }
  78492. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78493. result.scaleToRef(2, result);
  78494. result.a = 1 + 0.01 * saturation;
  78495. };
  78496. /**
  78497. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78498. * @param value The input slider value in range [-100,100].
  78499. * @returns Adjusted value.
  78500. */
  78501. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78502. value /= 100;
  78503. var x = Math.abs(value);
  78504. x = Math.pow(x, 2);
  78505. if (value < 0) {
  78506. x *= -1;
  78507. }
  78508. x *= 100;
  78509. return x;
  78510. };
  78511. /**
  78512. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78513. * @param hue The hue (H) input.
  78514. * @param saturation The saturation (S) input.
  78515. * @param brightness The brightness (B) input.
  78516. * @result An RGBA color represented as Vector4.
  78517. */
  78518. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78519. var h = ColorCurves.clamp(hue, 0, 360);
  78520. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78521. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78522. if (s === 0) {
  78523. result.r = v;
  78524. result.g = v;
  78525. result.b = v;
  78526. }
  78527. else {
  78528. // sector 0 to 5
  78529. h /= 60;
  78530. var i = Math.floor(h);
  78531. // fractional part of h
  78532. var f = h - i;
  78533. var p = v * (1 - s);
  78534. var q = v * (1 - s * f);
  78535. var t = v * (1 - s * (1 - f));
  78536. switch (i) {
  78537. case 0:
  78538. result.r = v;
  78539. result.g = t;
  78540. result.b = p;
  78541. break;
  78542. case 1:
  78543. result.r = q;
  78544. result.g = v;
  78545. result.b = p;
  78546. break;
  78547. case 2:
  78548. result.r = p;
  78549. result.g = v;
  78550. result.b = t;
  78551. break;
  78552. case 3:
  78553. result.r = p;
  78554. result.g = q;
  78555. result.b = v;
  78556. break;
  78557. case 4:
  78558. result.r = t;
  78559. result.g = p;
  78560. result.b = v;
  78561. break;
  78562. default: // case 5:
  78563. result.r = v;
  78564. result.g = p;
  78565. result.b = q;
  78566. break;
  78567. }
  78568. }
  78569. result.a = 1;
  78570. };
  78571. /**
  78572. * Returns a value clamped between min and max
  78573. * @param value The value to clamp
  78574. * @param min The minimum of value
  78575. * @param max The maximum of value
  78576. * @returns The clamped value.
  78577. */
  78578. ColorCurves.clamp = function (value, min, max) {
  78579. return Math.min(Math.max(value, min), max);
  78580. };
  78581. /**
  78582. * Clones the current color curve instance.
  78583. * @return The cloned curves
  78584. */
  78585. ColorCurves.prototype.clone = function () {
  78586. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78587. };
  78588. /**
  78589. * Serializes the current color curve instance to a json representation.
  78590. * @return a JSON representation
  78591. */
  78592. ColorCurves.prototype.serialize = function () {
  78593. return BABYLON.SerializationHelper.Serialize(this);
  78594. };
  78595. /**
  78596. * Parses the color curve from a json representation.
  78597. * @param source the JSON source to parse
  78598. * @return The parsed curves
  78599. */
  78600. ColorCurves.Parse = function (source) {
  78601. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78602. };
  78603. __decorate([
  78604. BABYLON.serialize()
  78605. ], ColorCurves.prototype, "_globalHue", void 0);
  78606. __decorate([
  78607. BABYLON.serialize()
  78608. ], ColorCurves.prototype, "_globalDensity", void 0);
  78609. __decorate([
  78610. BABYLON.serialize()
  78611. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78612. __decorate([
  78613. BABYLON.serialize()
  78614. ], ColorCurves.prototype, "_globalExposure", void 0);
  78615. __decorate([
  78616. BABYLON.serialize()
  78617. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78618. __decorate([
  78619. BABYLON.serialize()
  78620. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78621. __decorate([
  78622. BABYLON.serialize()
  78623. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78624. __decorate([
  78625. BABYLON.serialize()
  78626. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78627. __decorate([
  78628. BABYLON.serialize()
  78629. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78630. __decorate([
  78631. BABYLON.serialize()
  78632. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78633. __decorate([
  78634. BABYLON.serialize()
  78635. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78636. __decorate([
  78637. BABYLON.serialize()
  78638. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78639. return ColorCurves;
  78640. }());
  78641. BABYLON.ColorCurves = ColorCurves;
  78642. })(BABYLON || (BABYLON = {}));
  78643. //# sourceMappingURL=babylon.colorCurves.js.map
  78644. var BABYLON;
  78645. (function (BABYLON) {
  78646. var RefractionPostProcess = /** @class */ (function (_super) {
  78647. __extends(RefractionPostProcess, _super);
  78648. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78649. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78650. _this.color = color;
  78651. _this.depth = depth;
  78652. _this.colorLevel = colorLevel;
  78653. _this._ownRefractionTexture = true;
  78654. _this.onActivateObservable.add(function (cam) {
  78655. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78656. });
  78657. _this.onApplyObservable.add(function (effect) {
  78658. effect.setColor3("baseColor", _this.color);
  78659. effect.setFloat("depth", _this.depth);
  78660. effect.setFloat("colorLevel", _this.colorLevel);
  78661. effect.setTexture("refractionSampler", _this._refTexture);
  78662. });
  78663. return _this;
  78664. }
  78665. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78666. /**
  78667. * Gets or sets the refraction texture
  78668. * Please note that you are responsible for disposing the texture if you set it manually
  78669. */
  78670. get: function () {
  78671. return this._refTexture;
  78672. },
  78673. set: function (value) {
  78674. if (this._refTexture && this._ownRefractionTexture) {
  78675. this._refTexture.dispose();
  78676. }
  78677. this._refTexture = value;
  78678. this._ownRefractionTexture = false;
  78679. },
  78680. enumerable: true,
  78681. configurable: true
  78682. });
  78683. // Methods
  78684. RefractionPostProcess.prototype.dispose = function (camera) {
  78685. if (this._refTexture && this._ownRefractionTexture) {
  78686. this._refTexture.dispose();
  78687. this._refTexture = null;
  78688. }
  78689. _super.prototype.dispose.call(this, camera);
  78690. };
  78691. return RefractionPostProcess;
  78692. }(BABYLON.PostProcess));
  78693. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78694. })(BABYLON || (BABYLON = {}));
  78695. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78696. var BABYLON;
  78697. (function (BABYLON) {
  78698. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78699. __extends(BlackAndWhitePostProcess, _super);
  78700. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78701. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78702. _this.degree = 1;
  78703. _this.onApplyObservable.add(function (effect) {
  78704. effect.setFloat("degree", _this.degree);
  78705. });
  78706. return _this;
  78707. }
  78708. return BlackAndWhitePostProcess;
  78709. }(BABYLON.PostProcess));
  78710. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78711. })(BABYLON || (BABYLON = {}));
  78712. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78713. var BABYLON;
  78714. (function (BABYLON) {
  78715. /**
  78716. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78717. * input texture to perform effects such as edge detection or sharpening
  78718. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78719. */
  78720. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78721. __extends(ConvolutionPostProcess, _super);
  78722. /**
  78723. * Creates a new instance ConvolutionPostProcess
  78724. * @param name The name of the effect.
  78725. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78726. * @param options The required width/height ratio to downsize to before computing the render pass.
  78727. * @param camera The camera to apply the render pass to.
  78728. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78729. * @param engine The engine which the post process will be applied. (default: current engine)
  78730. * @param reusable If the post process can be reused on the same frame. (default: false)
  78731. * @param textureType Type of textures used when performing the post process. (default: 0)
  78732. */
  78733. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78734. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78735. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78736. _this.kernel = kernel;
  78737. _this.onApply = function (effect) {
  78738. effect.setFloat2("screenSize", _this.width, _this.height);
  78739. effect.setArray("kernel", _this.kernel);
  78740. };
  78741. return _this;
  78742. }
  78743. // Statics
  78744. /**
  78745. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78746. */
  78747. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78748. /**
  78749. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78750. */
  78751. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78752. /**
  78753. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78754. */
  78755. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78756. /**
  78757. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78758. */
  78759. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78760. /**
  78761. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78762. */
  78763. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78764. /**
  78765. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78766. */
  78767. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78768. return ConvolutionPostProcess;
  78769. }(BABYLON.PostProcess));
  78770. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78771. })(BABYLON || (BABYLON = {}));
  78772. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78773. var BABYLON;
  78774. (function (BABYLON) {
  78775. var FilterPostProcess = /** @class */ (function (_super) {
  78776. __extends(FilterPostProcess, _super);
  78777. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78778. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78779. _this.kernelMatrix = kernelMatrix;
  78780. _this.onApply = function (effect) {
  78781. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78782. };
  78783. return _this;
  78784. }
  78785. return FilterPostProcess;
  78786. }(BABYLON.PostProcess));
  78787. BABYLON.FilterPostProcess = FilterPostProcess;
  78788. })(BABYLON || (BABYLON = {}));
  78789. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78790. var BABYLON;
  78791. (function (BABYLON) {
  78792. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78793. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78794. __extends(VolumetricLightScatteringPostProcess, _super);
  78795. /**
  78796. * @constructor
  78797. * @param {string} name - The post-process name
  78798. * @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)
  78799. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78800. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78801. * @param {number} samples - The post-process quality, default 100
  78802. * @param {number} samplingMode - The post-process filtering mode
  78803. * @param {BABYLON.Engine} engine - The babylon engine
  78804. * @param {boolean} reusable - If the post-process is reusable
  78805. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78806. */
  78807. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78808. if (samples === void 0) { samples = 100; }
  78809. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78810. 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;
  78811. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78812. /**
  78813. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78814. */
  78815. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78816. /**
  78817. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78818. */
  78819. _this.useCustomMeshPosition = false;
  78820. /**
  78821. * If the post-process should inverse the light scattering direction
  78822. */
  78823. _this.invert = true;
  78824. /**
  78825. * Array containing the excluded meshes not rendered in the internal pass
  78826. */
  78827. _this.excludedMeshes = new Array();
  78828. /**
  78829. * Controls the overall intensity of the post-process
  78830. */
  78831. _this.exposure = 0.3;
  78832. /**
  78833. * Dissipates each sample's contribution in range [0, 1]
  78834. */
  78835. _this.decay = 0.96815;
  78836. /**
  78837. * Controls the overall intensity of each sample
  78838. */
  78839. _this.weight = 0.58767;
  78840. /**
  78841. * Controls the density of each sample
  78842. */
  78843. _this.density = 0.926;
  78844. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78845. engine = scene.getEngine();
  78846. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78847. // Configure mesh
  78848. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78849. // Configure
  78850. _this._createPass(scene, ratio.passRatio || ratio);
  78851. _this.onActivate = function (camera) {
  78852. if (!_this.isSupported) {
  78853. _this.dispose(camera);
  78854. }
  78855. _this.onActivate = null;
  78856. };
  78857. _this.onApplyObservable.add(function (effect) {
  78858. _this._updateMeshScreenCoordinates(scene);
  78859. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78860. effect.setFloat("exposure", _this.exposure);
  78861. effect.setFloat("decay", _this.decay);
  78862. effect.setFloat("weight", _this.weight);
  78863. effect.setFloat("density", _this.density);
  78864. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78865. });
  78866. return _this;
  78867. }
  78868. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78869. get: function () {
  78870. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78871. return false;
  78872. },
  78873. set: function (useDiffuseColor) {
  78874. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78875. },
  78876. enumerable: true,
  78877. configurable: true
  78878. });
  78879. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78880. return "VolumetricLightScatteringPostProcess";
  78881. };
  78882. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78883. var mesh = subMesh.getMesh();
  78884. // Render this.mesh as default
  78885. if (mesh === this.mesh && mesh.material) {
  78886. return mesh.material.isReady(mesh);
  78887. }
  78888. var defines = [];
  78889. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78890. var material = subMesh.getMaterial();
  78891. // Alpha test
  78892. if (material) {
  78893. if (material.needAlphaTesting()) {
  78894. defines.push("#define ALPHATEST");
  78895. }
  78896. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78897. attribs.push(BABYLON.VertexBuffer.UVKind);
  78898. defines.push("#define UV1");
  78899. }
  78900. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78901. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78902. defines.push("#define UV2");
  78903. }
  78904. }
  78905. // Bones
  78906. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78909. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78910. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78911. }
  78912. else {
  78913. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78914. }
  78915. // Instances
  78916. if (useInstances) {
  78917. defines.push("#define INSTANCES");
  78918. attribs.push("world0");
  78919. attribs.push("world1");
  78920. attribs.push("world2");
  78921. attribs.push("world3");
  78922. }
  78923. // Get correct effect
  78924. var join = defines.join("\n");
  78925. if (this._cachedDefines !== join) {
  78926. this._cachedDefines = join;
  78927. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78928. }
  78929. return this._volumetricLightScatteringPass.isReady();
  78930. };
  78931. /**
  78932. * Sets the new light position for light scattering effect
  78933. * @param {BABYLON.Vector3} The new custom light position
  78934. */
  78935. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78936. this.customMeshPosition = position;
  78937. };
  78938. /**
  78939. * Returns the light position for light scattering effect
  78940. * @return {BABYLON.Vector3} The custom light position
  78941. */
  78942. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78943. return this.customMeshPosition;
  78944. };
  78945. /**
  78946. * Disposes the internal assets and detaches the post-process from the camera
  78947. */
  78948. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78949. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78950. if (rttIndex !== -1) {
  78951. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78952. }
  78953. this._volumetricLightScatteringRTT.dispose();
  78954. _super.prototype.dispose.call(this, camera);
  78955. };
  78956. /**
  78957. * Returns the render target texture used by the post-process
  78958. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78959. */
  78960. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78961. return this._volumetricLightScatteringRTT;
  78962. };
  78963. // Private methods
  78964. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78965. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78966. return true;
  78967. }
  78968. return false;
  78969. };
  78970. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78971. var _this = this;
  78972. var engine = scene.getEngine();
  78973. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78974. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78975. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78976. this._volumetricLightScatteringRTT.renderList = null;
  78977. this._volumetricLightScatteringRTT.renderParticles = false;
  78978. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78979. var camera = this.getCamera();
  78980. if (camera) {
  78981. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78982. }
  78983. else {
  78984. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78985. }
  78986. // Custom render function for submeshes
  78987. var renderSubMesh = function (subMesh) {
  78988. var mesh = subMesh.getRenderingMesh();
  78989. if (_this._meshExcluded(mesh)) {
  78990. return;
  78991. }
  78992. var material = subMesh.getMaterial();
  78993. if (!material) {
  78994. return;
  78995. }
  78996. var scene = mesh.getScene();
  78997. var engine = scene.getEngine();
  78998. // Culling
  78999. engine.setState(material.backFaceCulling);
  79000. // Managing instances
  79001. var batch = mesh._getInstancesRenderList(subMesh._id);
  79002. if (batch.mustReturn) {
  79003. return;
  79004. }
  79005. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79006. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  79007. var effect = _this._volumetricLightScatteringPass;
  79008. if (mesh === _this.mesh) {
  79009. if (subMesh.effect) {
  79010. effect = subMesh.effect;
  79011. }
  79012. else {
  79013. effect = material.getEffect();
  79014. }
  79015. }
  79016. engine.enableEffect(effect);
  79017. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  79018. if (mesh === _this.mesh) {
  79019. material.bind(mesh.getWorldMatrix(), mesh);
  79020. }
  79021. else {
  79022. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  79023. // Alpha test
  79024. if (material && material.needAlphaTesting()) {
  79025. var alphaTexture = material.getAlphaTestTexture();
  79026. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  79027. if (alphaTexture) {
  79028. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79029. }
  79030. }
  79031. // Bones
  79032. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79033. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79034. }
  79035. }
  79036. // Draw
  79037. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  79038. }
  79039. };
  79040. // Render target texture callbacks
  79041. var savedSceneClearColor;
  79042. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  79043. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  79044. savedSceneClearColor = scene.clearColor;
  79045. scene.clearColor = sceneClearColor;
  79046. });
  79047. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  79048. scene.clearColor = savedSceneClearColor;
  79049. });
  79050. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79051. var engine = scene.getEngine();
  79052. var index;
  79053. if (depthOnlySubMeshes.length) {
  79054. engine.setColorWrite(false);
  79055. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79056. renderSubMesh(depthOnlySubMeshes.data[index]);
  79057. }
  79058. engine.setColorWrite(true);
  79059. }
  79060. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79061. renderSubMesh(opaqueSubMeshes.data[index]);
  79062. }
  79063. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79064. renderSubMesh(alphaTestSubMeshes.data[index]);
  79065. }
  79066. if (transparentSubMeshes.length) {
  79067. // Sort sub meshes
  79068. for (index = 0; index < transparentSubMeshes.length; index++) {
  79069. var submesh = transparentSubMeshes.data[index];
  79070. var boundingInfo = submesh.getBoundingInfo();
  79071. if (boundingInfo && scene.activeCamera) {
  79072. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  79073. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  79074. }
  79075. }
  79076. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  79077. sortedArray.sort(function (a, b) {
  79078. // Alpha index first
  79079. if (a._alphaIndex > b._alphaIndex) {
  79080. return 1;
  79081. }
  79082. if (a._alphaIndex < b._alphaIndex) {
  79083. return -1;
  79084. }
  79085. // Then distance to camera
  79086. if (a._distanceToCamera < b._distanceToCamera) {
  79087. return 1;
  79088. }
  79089. if (a._distanceToCamera > b._distanceToCamera) {
  79090. return -1;
  79091. }
  79092. return 0;
  79093. });
  79094. // Render sub meshes
  79095. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  79096. for (index = 0; index < sortedArray.length; index++) {
  79097. renderSubMesh(sortedArray[index]);
  79098. }
  79099. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  79100. }
  79101. };
  79102. };
  79103. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  79104. var transform = scene.getTransformMatrix();
  79105. var meshPosition;
  79106. if (this.useCustomMeshPosition) {
  79107. meshPosition = this.customMeshPosition;
  79108. }
  79109. else if (this.attachedNode) {
  79110. meshPosition = this.attachedNode.position;
  79111. }
  79112. else {
  79113. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  79114. }
  79115. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  79116. this._screenCoordinates.x = pos.x / this._viewPort.width;
  79117. this._screenCoordinates.y = pos.y / this._viewPort.height;
  79118. if (this.invert)
  79119. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  79120. };
  79121. // Static methods
  79122. /**
  79123. * Creates a default mesh for the Volumeric Light Scattering post-process
  79124. * @param {string} The mesh name
  79125. * @param {BABYLON.Scene} The scene where to create the mesh
  79126. * @return {BABYLON.Mesh} the default mesh
  79127. */
  79128. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  79129. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  79130. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  79131. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  79132. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  79133. mesh.material = material;
  79134. return mesh;
  79135. };
  79136. __decorate([
  79137. BABYLON.serializeAsVector3()
  79138. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  79139. __decorate([
  79140. BABYLON.serialize()
  79141. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  79142. __decorate([
  79143. BABYLON.serialize()
  79144. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  79145. __decorate([
  79146. BABYLON.serializeAsMeshReference()
  79147. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  79148. __decorate([
  79149. BABYLON.serialize()
  79150. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  79151. __decorate([
  79152. BABYLON.serialize()
  79153. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  79154. __decorate([
  79155. BABYLON.serialize()
  79156. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  79157. __decorate([
  79158. BABYLON.serialize()
  79159. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  79160. __decorate([
  79161. BABYLON.serialize()
  79162. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  79163. return VolumetricLightScatteringPostProcess;
  79164. }(BABYLON.PostProcess));
  79165. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  79166. })(BABYLON || (BABYLON = {}));
  79167. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  79168. //
  79169. // This post-process allows the modification of rendered colors by using
  79170. // a 'look-up table' (LUT). This effect is also called Color Grading.
  79171. //
  79172. // The object needs to be provided an url to a texture containing the color
  79173. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  79174. // Use an image editing software to tweak the LUT to match your needs.
  79175. //
  79176. // For an example of a color LUT, see here:
  79177. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  79178. // For explanations on color grading, see here:
  79179. // http://udn.epicgames.com/Three/ColorGrading.html
  79180. //
  79181. var BABYLON;
  79182. (function (BABYLON) {
  79183. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  79184. __extends(ColorCorrectionPostProcess, _super);
  79185. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  79186. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  79187. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79188. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  79189. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79190. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79191. _this.onApply = function (effect) {
  79192. effect.setTexture("colorTable", _this._colorTableTexture);
  79193. };
  79194. return _this;
  79195. }
  79196. return ColorCorrectionPostProcess;
  79197. }(BABYLON.PostProcess));
  79198. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  79199. })(BABYLON || (BABYLON = {}));
  79200. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  79201. var BABYLON;
  79202. (function (BABYLON) {
  79203. /** Defines operator used for tonemapping */
  79204. var TonemappingOperator;
  79205. (function (TonemappingOperator) {
  79206. /** Hable */
  79207. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  79208. /** Reinhard */
  79209. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  79210. /** HejiDawson */
  79211. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  79212. /** Photographic */
  79213. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  79214. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  79215. ;
  79216. /**
  79217. * Defines a post process to apply tone mapping
  79218. */
  79219. var TonemapPostProcess = /** @class */ (function (_super) {
  79220. __extends(TonemapPostProcess, _super);
  79221. /**
  79222. * Creates a new TonemapPostProcess
  79223. * @param name defines the name of the postprocess
  79224. * @param _operator defines the operator to use
  79225. * @param exposureAdjustment defines the required exposure adjustement
  79226. * @param camera defines the camera to use (can be null)
  79227. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  79228. * @param engine defines the hosting engine (can be ignore if camera is set)
  79229. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  79230. */
  79231. function TonemapPostProcess(name, _operator,
  79232. /** Defines the required exposure adjustement */
  79233. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79234. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79235. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79236. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79237. _this._operator = _operator;
  79238. _this.exposureAdjustment = exposureAdjustment;
  79239. var defines = "#define ";
  79240. if (_this._operator === TonemappingOperator.Hable)
  79241. defines += "HABLE_TONEMAPPING";
  79242. else if (_this._operator === TonemappingOperator.Reinhard)
  79243. defines += "REINHARD_TONEMAPPING";
  79244. else if (_this._operator === TonemappingOperator.HejiDawson)
  79245. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79246. else if (_this._operator === TonemappingOperator.Photographic)
  79247. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79248. //sadly a second call to create the effect.
  79249. _this.updateEffect(defines);
  79250. _this.onApply = function (effect) {
  79251. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79252. };
  79253. return _this;
  79254. }
  79255. return TonemapPostProcess;
  79256. }(BABYLON.PostProcess));
  79257. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79258. })(BABYLON || (BABYLON = {}));
  79259. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79260. var BABYLON;
  79261. (function (BABYLON) {
  79262. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79263. __extends(DisplayPassPostProcess, _super);
  79264. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79265. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79266. }
  79267. return DisplayPassPostProcess;
  79268. }(BABYLON.PostProcess));
  79269. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79270. })(BABYLON || (BABYLON = {}));
  79271. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79272. var BABYLON;
  79273. (function (BABYLON) {
  79274. var HighlightsPostProcess = /** @class */ (function (_super) {
  79275. __extends(HighlightsPostProcess, _super);
  79276. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79277. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79278. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79279. }
  79280. return HighlightsPostProcess;
  79281. }(BABYLON.PostProcess));
  79282. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79283. })(BABYLON || (BABYLON = {}));
  79284. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79285. var BABYLON;
  79286. (function (BABYLON) {
  79287. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79288. __extends(ImageProcessingPostProcess, _super);
  79289. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79290. if (camera === void 0) { camera = null; }
  79291. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79292. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79293. _this._fromLinearSpace = true;
  79294. /**
  79295. * Defines cache preventing GC.
  79296. */
  79297. _this._defines = {
  79298. IMAGEPROCESSING: false,
  79299. VIGNETTE: false,
  79300. VIGNETTEBLENDMODEMULTIPLY: false,
  79301. VIGNETTEBLENDMODEOPAQUE: false,
  79302. TONEMAPPING: false,
  79303. CONTRAST: false,
  79304. COLORCURVES: false,
  79305. COLORGRADING: false,
  79306. COLORGRADING3D: false,
  79307. FROMLINEARSPACE: false,
  79308. SAMPLER3DGREENDEPTH: false,
  79309. SAMPLER3DBGRMAP: false,
  79310. IMAGEPROCESSINGPOSTPROCESS: false,
  79311. EXPOSURE: false,
  79312. };
  79313. // Setup the configuration as forced by the constructor. This would then not force the
  79314. // scene materials output in linear space and let untouched the default forward pass.
  79315. if (imageProcessingConfiguration) {
  79316. imageProcessingConfiguration.applyByPostProcess = true;
  79317. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79318. // This will cause the shader to be compiled
  79319. _this.fromLinearSpace = false;
  79320. }
  79321. // Setup the default processing configuration to the scene.
  79322. else {
  79323. _this._attachImageProcessingConfiguration(null, true);
  79324. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79325. }
  79326. _this.onApply = function (effect) {
  79327. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79328. };
  79329. return _this;
  79330. }
  79331. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79332. /**
  79333. * Gets the image processing configuration used either in this material.
  79334. */
  79335. get: function () {
  79336. return this._imageProcessingConfiguration;
  79337. },
  79338. /**
  79339. * Sets the Default image processing configuration used either in the this material.
  79340. *
  79341. * If sets to null, the scene one is in use.
  79342. */
  79343. set: function (value) {
  79344. this._attachImageProcessingConfiguration(value);
  79345. },
  79346. enumerable: true,
  79347. configurable: true
  79348. });
  79349. /**
  79350. * Attaches a new image processing configuration to the PBR Material.
  79351. * @param configuration
  79352. */
  79353. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79354. var _this = this;
  79355. if (doNotBuild === void 0) { doNotBuild = false; }
  79356. if (configuration === this._imageProcessingConfiguration) {
  79357. return;
  79358. }
  79359. // Detaches observer.
  79360. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79361. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79362. }
  79363. // Pick the scene configuration if needed.
  79364. if (!configuration) {
  79365. var scene = null;
  79366. var engine = this.getEngine();
  79367. var camera = this.getCamera();
  79368. if (camera) {
  79369. scene = camera.getScene();
  79370. }
  79371. else if (engine && engine.scenes) {
  79372. var scenes = engine.scenes;
  79373. scene = scenes[scenes.length - 1];
  79374. }
  79375. else {
  79376. scene = BABYLON.Engine.LastCreatedScene;
  79377. }
  79378. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79379. }
  79380. else {
  79381. this._imageProcessingConfiguration = configuration;
  79382. }
  79383. // Attaches observer.
  79384. if (this._imageProcessingConfiguration) {
  79385. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79386. _this._updateParameters();
  79387. });
  79388. }
  79389. // Ensure the effect will be rebuilt.
  79390. if (!doNotBuild) {
  79391. this._updateParameters();
  79392. }
  79393. };
  79394. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79395. /**
  79396. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79397. */
  79398. get: function () {
  79399. return this.imageProcessingConfiguration.colorCurves;
  79400. },
  79401. /**
  79402. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79403. */
  79404. set: function (value) {
  79405. this.imageProcessingConfiguration.colorCurves = value;
  79406. },
  79407. enumerable: true,
  79408. configurable: true
  79409. });
  79410. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79411. /**
  79412. * Gets wether the color curves effect is enabled.
  79413. */
  79414. get: function () {
  79415. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79416. },
  79417. /**
  79418. * Sets wether the color curves effect is enabled.
  79419. */
  79420. set: function (value) {
  79421. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79422. },
  79423. enumerable: true,
  79424. configurable: true
  79425. });
  79426. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79427. /**
  79428. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79429. */
  79430. get: function () {
  79431. return this.imageProcessingConfiguration.colorGradingTexture;
  79432. },
  79433. /**
  79434. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79435. */
  79436. set: function (value) {
  79437. this.imageProcessingConfiguration.colorGradingTexture = value;
  79438. },
  79439. enumerable: true,
  79440. configurable: true
  79441. });
  79442. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79443. /**
  79444. * Gets wether the color grading effect is enabled.
  79445. */
  79446. get: function () {
  79447. return this.imageProcessingConfiguration.colorGradingEnabled;
  79448. },
  79449. /**
  79450. * Gets wether the color grading effect is enabled.
  79451. */
  79452. set: function (value) {
  79453. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79454. },
  79455. enumerable: true,
  79456. configurable: true
  79457. });
  79458. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79459. /**
  79460. * Gets exposure used in the effect.
  79461. */
  79462. get: function () {
  79463. return this.imageProcessingConfiguration.exposure;
  79464. },
  79465. /**
  79466. * Sets exposure used in the effect.
  79467. */
  79468. set: function (value) {
  79469. this.imageProcessingConfiguration.exposure = value;
  79470. },
  79471. enumerable: true,
  79472. configurable: true
  79473. });
  79474. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79475. /**
  79476. * Gets wether tonemapping is enabled or not.
  79477. */
  79478. get: function () {
  79479. return this._imageProcessingConfiguration.toneMappingEnabled;
  79480. },
  79481. /**
  79482. * Sets wether tonemapping is enabled or not
  79483. */
  79484. set: function (value) {
  79485. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79486. },
  79487. enumerable: true,
  79488. configurable: true
  79489. });
  79490. ;
  79491. ;
  79492. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79493. /**
  79494. * Gets contrast used in the effect.
  79495. */
  79496. get: function () {
  79497. return this.imageProcessingConfiguration.contrast;
  79498. },
  79499. /**
  79500. * Sets contrast used in the effect.
  79501. */
  79502. set: function (value) {
  79503. this.imageProcessingConfiguration.contrast = value;
  79504. },
  79505. enumerable: true,
  79506. configurable: true
  79507. });
  79508. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79509. /**
  79510. * Gets Vignette stretch size.
  79511. */
  79512. get: function () {
  79513. return this.imageProcessingConfiguration.vignetteStretch;
  79514. },
  79515. /**
  79516. * Sets Vignette stretch size.
  79517. */
  79518. set: function (value) {
  79519. this.imageProcessingConfiguration.vignetteStretch = value;
  79520. },
  79521. enumerable: true,
  79522. configurable: true
  79523. });
  79524. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79525. /**
  79526. * Gets Vignette centre X Offset.
  79527. */
  79528. get: function () {
  79529. return this.imageProcessingConfiguration.vignetteCentreX;
  79530. },
  79531. /**
  79532. * Sets Vignette centre X Offset.
  79533. */
  79534. set: function (value) {
  79535. this.imageProcessingConfiguration.vignetteCentreX = value;
  79536. },
  79537. enumerable: true,
  79538. configurable: true
  79539. });
  79540. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79541. /**
  79542. * Gets Vignette centre Y Offset.
  79543. */
  79544. get: function () {
  79545. return this.imageProcessingConfiguration.vignetteCentreY;
  79546. },
  79547. /**
  79548. * Sets Vignette centre Y Offset.
  79549. */
  79550. set: function (value) {
  79551. this.imageProcessingConfiguration.vignetteCentreY = value;
  79552. },
  79553. enumerable: true,
  79554. configurable: true
  79555. });
  79556. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79557. /**
  79558. * Gets Vignette weight or intensity of the vignette effect.
  79559. */
  79560. get: function () {
  79561. return this.imageProcessingConfiguration.vignetteWeight;
  79562. },
  79563. /**
  79564. * Sets Vignette weight or intensity of the vignette effect.
  79565. */
  79566. set: function (value) {
  79567. this.imageProcessingConfiguration.vignetteWeight = value;
  79568. },
  79569. enumerable: true,
  79570. configurable: true
  79571. });
  79572. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79573. /**
  79574. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79575. * if vignetteEnabled is set to true.
  79576. */
  79577. get: function () {
  79578. return this.imageProcessingConfiguration.vignetteColor;
  79579. },
  79580. /**
  79581. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79582. * if vignetteEnabled is set to true.
  79583. */
  79584. set: function (value) {
  79585. this.imageProcessingConfiguration.vignetteColor = value;
  79586. },
  79587. enumerable: true,
  79588. configurable: true
  79589. });
  79590. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79591. /**
  79592. * Gets Camera field of view used by the Vignette effect.
  79593. */
  79594. get: function () {
  79595. return this.imageProcessingConfiguration.vignetteCameraFov;
  79596. },
  79597. /**
  79598. * Sets Camera field of view used by the Vignette effect.
  79599. */
  79600. set: function (value) {
  79601. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79602. },
  79603. enumerable: true,
  79604. configurable: true
  79605. });
  79606. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79607. /**
  79608. * Gets the vignette blend mode allowing different kind of effect.
  79609. */
  79610. get: function () {
  79611. return this.imageProcessingConfiguration.vignetteBlendMode;
  79612. },
  79613. /**
  79614. * Sets the vignette blend mode allowing different kind of effect.
  79615. */
  79616. set: function (value) {
  79617. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79618. },
  79619. enumerable: true,
  79620. configurable: true
  79621. });
  79622. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79623. /**
  79624. * Gets wether the vignette effect is enabled.
  79625. */
  79626. get: function () {
  79627. return this.imageProcessingConfiguration.vignetteEnabled;
  79628. },
  79629. /**
  79630. * Sets wether the vignette effect is enabled.
  79631. */
  79632. set: function (value) {
  79633. this.imageProcessingConfiguration.vignetteEnabled = value;
  79634. },
  79635. enumerable: true,
  79636. configurable: true
  79637. });
  79638. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79639. /**
  79640. * Gets wether the input of the processing is in Gamma or Linear Space.
  79641. */
  79642. get: function () {
  79643. return this._fromLinearSpace;
  79644. },
  79645. /**
  79646. * Sets wether the input of the processing is in Gamma or Linear Space.
  79647. */
  79648. set: function (value) {
  79649. if (this._fromLinearSpace === value) {
  79650. return;
  79651. }
  79652. this._fromLinearSpace = value;
  79653. this._updateParameters();
  79654. },
  79655. enumerable: true,
  79656. configurable: true
  79657. });
  79658. ImageProcessingPostProcess.prototype.getClassName = function () {
  79659. return "ImageProcessingPostProcess";
  79660. };
  79661. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79662. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79663. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79664. var defines = "";
  79665. for (var define in this._defines) {
  79666. if (this._defines[define]) {
  79667. defines += "#define " + define + ";\r\n";
  79668. }
  79669. }
  79670. var samplers = ["textureSampler"];
  79671. var uniforms = ["scale"];
  79672. if (BABYLON.ImageProcessingConfiguration) {
  79673. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79674. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79675. }
  79676. this.updateEffect(defines, uniforms, samplers);
  79677. };
  79678. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79679. _super.prototype.dispose.call(this, camera);
  79680. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79681. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79682. }
  79683. if (this._imageProcessingConfiguration) {
  79684. this.imageProcessingConfiguration.applyByPostProcess = false;
  79685. }
  79686. };
  79687. __decorate([
  79688. BABYLON.serialize()
  79689. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79690. return ImageProcessingPostProcess;
  79691. }(BABYLON.PostProcess));
  79692. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79693. })(BABYLON || (BABYLON = {}));
  79694. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79695. var BABYLON;
  79696. (function (BABYLON) {
  79697. /**
  79698. * Class used to store bone information
  79699. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79700. */
  79701. var Bone = /** @class */ (function (_super) {
  79702. __extends(Bone, _super);
  79703. /**
  79704. * Create a new bone
  79705. * @param name defines the bone name
  79706. * @param skeleton defines the parent skeleton
  79707. * @param parentBone defines the parent (can be null if the bone is the root)
  79708. * @param localMatrix defines the local matrix
  79709. * @param restPose defines the rest pose matrix
  79710. * @param baseMatrix defines the base matrix
  79711. * @param index defines index of the bone in the hiearchy
  79712. */
  79713. function Bone(
  79714. /**
  79715. * defines the bone name
  79716. */
  79717. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79718. if (parentBone === void 0) { parentBone = null; }
  79719. if (localMatrix === void 0) { localMatrix = null; }
  79720. if (restPose === void 0) { restPose = null; }
  79721. if (baseMatrix === void 0) { baseMatrix = null; }
  79722. if (index === void 0) { index = null; }
  79723. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79724. _this.name = name;
  79725. /**
  79726. * Gets the list of child bones
  79727. */
  79728. _this.children = new Array();
  79729. /** Gets the animations associated with this bone */
  79730. _this.animations = new Array();
  79731. /**
  79732. * @hidden Internal only
  79733. * Set this value to map this bone to a different index in the transform matrices
  79734. * Set this value to -1 to exclude the bone from the transform matrices
  79735. */
  79736. _this._index = null;
  79737. _this._absoluteTransform = new BABYLON.Matrix();
  79738. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79739. _this._scalingDeterminant = 1;
  79740. _this._worldTransform = new BABYLON.Matrix();
  79741. _this._needToDecompose = true;
  79742. _this._needToCompose = false;
  79743. _this._skeleton = skeleton;
  79744. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79745. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79746. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79747. _this._index = index;
  79748. skeleton.bones.push(_this);
  79749. _this.setParent(parentBone, false);
  79750. if (baseMatrix || localMatrix) {
  79751. _this._updateDifferenceMatrix();
  79752. }
  79753. return _this;
  79754. }
  79755. Object.defineProperty(Bone.prototype, "_matrix", {
  79756. /** @hidden */
  79757. get: function () {
  79758. this._compose();
  79759. return this._localMatrix;
  79760. },
  79761. /** @hidden */
  79762. set: function (value) {
  79763. this._localMatrix.copyFrom(value);
  79764. this._needToDecompose = true;
  79765. },
  79766. enumerable: true,
  79767. configurable: true
  79768. });
  79769. // Members
  79770. /**
  79771. * Gets the parent skeleton
  79772. * @returns a skeleton
  79773. */
  79774. Bone.prototype.getSkeleton = function () {
  79775. return this._skeleton;
  79776. };
  79777. /**
  79778. * Gets parent bone
  79779. * @returns a bone or null if the bone is the root of the bone hierarchy
  79780. */
  79781. Bone.prototype.getParent = function () {
  79782. return this._parent;
  79783. };
  79784. /**
  79785. * Sets the parent bone
  79786. * @param parent defines the parent (can be null if the bone is the root)
  79787. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79788. */
  79789. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79790. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79791. if (this._parent === parent) {
  79792. return;
  79793. }
  79794. if (this._parent) {
  79795. var index = this._parent.children.indexOf(this);
  79796. if (index !== -1) {
  79797. this._parent.children.splice(index, 1);
  79798. }
  79799. }
  79800. this._parent = parent;
  79801. if (this._parent) {
  79802. this._parent.children.push(this);
  79803. }
  79804. if (updateDifferenceMatrix) {
  79805. this._updateDifferenceMatrix();
  79806. }
  79807. this.markAsDirty();
  79808. };
  79809. /**
  79810. * Gets the local matrix
  79811. * @returns a matrix
  79812. */
  79813. Bone.prototype.getLocalMatrix = function () {
  79814. this._compose();
  79815. return this._localMatrix;
  79816. };
  79817. /**
  79818. * Gets the base matrix (initial matrix which remains unchanged)
  79819. * @returns a matrix
  79820. */
  79821. Bone.prototype.getBaseMatrix = function () {
  79822. return this._baseMatrix;
  79823. };
  79824. /**
  79825. * Gets the rest pose matrix
  79826. * @returns a matrix
  79827. */
  79828. Bone.prototype.getRestPose = function () {
  79829. return this._restPose;
  79830. };
  79831. /**
  79832. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79833. */
  79834. Bone.prototype.getWorldMatrix = function () {
  79835. return this._worldTransform;
  79836. };
  79837. /**
  79838. * Sets the local matrix to rest pose matrix
  79839. */
  79840. Bone.prototype.returnToRest = function () {
  79841. this.updateMatrix(this._restPose.clone());
  79842. };
  79843. /**
  79844. * Gets the inverse of the absolute transform matrix.
  79845. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79846. * @returns a matrix
  79847. */
  79848. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79849. return this._invertedAbsoluteTransform;
  79850. };
  79851. /**
  79852. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79853. * @returns a matrix
  79854. */
  79855. Bone.prototype.getAbsoluteTransform = function () {
  79856. return this._absoluteTransform;
  79857. };
  79858. Object.defineProperty(Bone.prototype, "position", {
  79859. // Properties (matches AbstractMesh properties)
  79860. /** Gets or sets current position (in local space) */
  79861. get: function () {
  79862. this._decompose();
  79863. return this._localPosition;
  79864. },
  79865. set: function (newPosition) {
  79866. this._decompose();
  79867. this._localPosition.copyFrom(newPosition);
  79868. this._markAsDirtyAndCompose();
  79869. },
  79870. enumerable: true,
  79871. configurable: true
  79872. });
  79873. Object.defineProperty(Bone.prototype, "rotation", {
  79874. /** Gets or sets current rotation (in local space) */
  79875. get: function () {
  79876. return this.getRotation();
  79877. },
  79878. set: function (newRotation) {
  79879. this.setRotation(newRotation);
  79880. },
  79881. enumerable: true,
  79882. configurable: true
  79883. });
  79884. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79885. /** Gets or sets current rotation quaternion (in local space) */
  79886. get: function () {
  79887. this._decompose();
  79888. return this._localRotation;
  79889. },
  79890. set: function (newRotation) {
  79891. this.setRotationQuaternion(newRotation);
  79892. },
  79893. enumerable: true,
  79894. configurable: true
  79895. });
  79896. Object.defineProperty(Bone.prototype, "scaling", {
  79897. /** Gets or sets current scaling (in local space) */
  79898. get: function () {
  79899. return this.getScale();
  79900. },
  79901. set: function (newScaling) {
  79902. this.setScale(newScaling);
  79903. },
  79904. enumerable: true,
  79905. configurable: true
  79906. });
  79907. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79908. /**
  79909. * Gets the animation properties override
  79910. */
  79911. get: function () {
  79912. return this._skeleton.animationPropertiesOverride;
  79913. },
  79914. enumerable: true,
  79915. configurable: true
  79916. });
  79917. // Methods
  79918. Bone.prototype._decompose = function () {
  79919. if (!this._needToDecompose) {
  79920. return;
  79921. }
  79922. this._needToDecompose = false;
  79923. if (!this._localScaling) {
  79924. this._localScaling = BABYLON.Vector3.Zero();
  79925. this._localRotation = BABYLON.Quaternion.Zero();
  79926. this._localPosition = BABYLON.Vector3.Zero();
  79927. }
  79928. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79929. };
  79930. Bone.prototype._compose = function () {
  79931. if (!this._needToCompose) {
  79932. return;
  79933. }
  79934. this._needToCompose = false;
  79935. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79936. };
  79937. /**
  79938. * Update the base and local matrices
  79939. * @param matrix defines the new base or local matrix
  79940. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79941. * @param updateLocalMatrix defines if the local matrix should be updated
  79942. */
  79943. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79944. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79945. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79946. this._baseMatrix.copyFrom(matrix);
  79947. if (updateDifferenceMatrix) {
  79948. this._updateDifferenceMatrix();
  79949. }
  79950. if (updateLocalMatrix) {
  79951. this._localMatrix.copyFrom(matrix);
  79952. this._markAsDirtyAndDecompose();
  79953. }
  79954. else {
  79955. this.markAsDirty();
  79956. }
  79957. };
  79958. /** @hidden */
  79959. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79960. if (updateChildren === void 0) { updateChildren = true; }
  79961. if (!rootMatrix) {
  79962. rootMatrix = this._baseMatrix;
  79963. }
  79964. if (this._parent) {
  79965. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79966. }
  79967. else {
  79968. this._absoluteTransform.copyFrom(rootMatrix);
  79969. }
  79970. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79971. if (updateChildren) {
  79972. for (var index = 0; index < this.children.length; index++) {
  79973. this.children[index]._updateDifferenceMatrix();
  79974. }
  79975. }
  79976. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79977. };
  79978. /**
  79979. * Flag the bone as dirty (Forcing it to update everything)
  79980. */
  79981. Bone.prototype.markAsDirty = function () {
  79982. this._currentRenderId++;
  79983. this._childRenderId++;
  79984. this._skeleton._markAsDirty();
  79985. };
  79986. Bone.prototype._markAsDirtyAndCompose = function () {
  79987. this.markAsDirty();
  79988. this._needToCompose = true;
  79989. };
  79990. Bone.prototype._markAsDirtyAndDecompose = function () {
  79991. this.markAsDirty();
  79992. this._needToDecompose = true;
  79993. };
  79994. /**
  79995. * Copy an animation range from another bone
  79996. * @param source defines the source bone
  79997. * @param rangeName defines the range name to copy
  79998. * @param frameOffset defines the frame offset
  79999. * @param rescaleAsRequired defines if rescaling must be applied if required
  80000. * @param skelDimensionsRatio defines the scaling ratio
  80001. * @returns true if operation was successful
  80002. */
  80003. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  80004. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80005. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  80006. // all animation may be coming from a library skeleton, so may need to create animation
  80007. if (this.animations.length === 0) {
  80008. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  80009. this.animations[0].setKeys([]);
  80010. }
  80011. // get animation info / verify there is such a range from the source bone
  80012. var sourceRange = source.animations[0].getRange(rangeName);
  80013. if (!sourceRange) {
  80014. return false;
  80015. }
  80016. var from = sourceRange.from;
  80017. var to = sourceRange.to;
  80018. var sourceKeys = source.animations[0].getKeys();
  80019. // rescaling prep
  80020. var sourceBoneLength = source.length;
  80021. var sourceParent = source.getParent();
  80022. var parent = this.getParent();
  80023. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  80024. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  80025. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  80026. var destKeys = this.animations[0].getKeys();
  80027. // loop vars declaration
  80028. var orig;
  80029. var origTranslation;
  80030. var mat;
  80031. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  80032. orig = sourceKeys[key];
  80033. if (orig.frame >= from && orig.frame <= to) {
  80034. if (rescaleAsRequired) {
  80035. mat = orig.value.clone();
  80036. // scale based on parent ratio, when bone has parent
  80037. if (parentScalingReqd) {
  80038. origTranslation = mat.getTranslation();
  80039. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  80040. // scale based on skeleton dimension ratio when root bone, and value is passed
  80041. }
  80042. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  80043. origTranslation = mat.getTranslation();
  80044. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  80045. // use original when root bone, and no data for skelDimensionsRatio
  80046. }
  80047. else {
  80048. mat = orig.value;
  80049. }
  80050. }
  80051. else {
  80052. mat = orig.value;
  80053. }
  80054. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  80055. }
  80056. }
  80057. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  80058. return true;
  80059. };
  80060. /**
  80061. * Translate the bone in local or world space
  80062. * @param vec The amount to translate the bone
  80063. * @param space The space that the translation is in
  80064. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80065. */
  80066. Bone.prototype.translate = function (vec, space, mesh) {
  80067. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80068. var lm = this.getLocalMatrix();
  80069. if (space == BABYLON.Space.LOCAL) {
  80070. lm.m[12] += vec.x;
  80071. lm.m[13] += vec.y;
  80072. lm.m[14] += vec.z;
  80073. }
  80074. else {
  80075. var wm = null;
  80076. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80077. if (mesh) {
  80078. wm = mesh.getWorldMatrix();
  80079. }
  80080. this._skeleton.computeAbsoluteTransforms();
  80081. var tmat = Bone._tmpMats[0];
  80082. var tvec = Bone._tmpVecs[0];
  80083. if (this._parent) {
  80084. if (mesh && wm) {
  80085. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80086. tmat.multiplyToRef(wm, tmat);
  80087. }
  80088. else {
  80089. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80090. }
  80091. }
  80092. tmat.m[12] = 0;
  80093. tmat.m[13] = 0;
  80094. tmat.m[14] = 0;
  80095. tmat.invert();
  80096. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  80097. lm.m[12] += tvec.x;
  80098. lm.m[13] += tvec.y;
  80099. lm.m[14] += tvec.z;
  80100. }
  80101. this._markAsDirtyAndDecompose();
  80102. };
  80103. /**
  80104. * Set the postion of the bone in local or world space
  80105. * @param position The position to set the bone
  80106. * @param space The space that the position is in
  80107. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80108. */
  80109. Bone.prototype.setPosition = function (position, space, mesh) {
  80110. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80111. var lm = this.getLocalMatrix();
  80112. if (space == BABYLON.Space.LOCAL) {
  80113. lm.m[12] = position.x;
  80114. lm.m[13] = position.y;
  80115. lm.m[14] = position.z;
  80116. }
  80117. else {
  80118. var wm = null;
  80119. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80120. if (mesh) {
  80121. wm = mesh.getWorldMatrix();
  80122. }
  80123. this._skeleton.computeAbsoluteTransforms();
  80124. var tmat = Bone._tmpMats[0];
  80125. var vec = Bone._tmpVecs[0];
  80126. if (this._parent) {
  80127. if (mesh && wm) {
  80128. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80129. tmat.multiplyToRef(wm, tmat);
  80130. }
  80131. else {
  80132. tmat.copyFrom(this._parent.getAbsoluteTransform());
  80133. }
  80134. }
  80135. tmat.invert();
  80136. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  80137. lm.m[12] = vec.x;
  80138. lm.m[13] = vec.y;
  80139. lm.m[14] = vec.z;
  80140. }
  80141. this._markAsDirtyAndDecompose();
  80142. };
  80143. /**
  80144. * Set the absolute position of the bone (world space)
  80145. * @param position The position to set the bone
  80146. * @param mesh The mesh that this bone is attached to
  80147. */
  80148. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  80149. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  80150. };
  80151. /**
  80152. * Scale the bone on the x, y and z axes (in local space)
  80153. * @param x The amount to scale the bone on the x axis
  80154. * @param y The amount to scale the bone on the y axis
  80155. * @param z The amount to scale the bone on the z axis
  80156. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  80157. */
  80158. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  80159. if (scaleChildren === void 0) { scaleChildren = false; }
  80160. var locMat = this.getLocalMatrix();
  80161. // Apply new scaling on top of current local matrix
  80162. var scaleMat = Bone._tmpMats[0];
  80163. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  80164. scaleMat.multiplyToRef(locMat, locMat);
  80165. // Invert scaling matrix and apply the inverse to all children
  80166. scaleMat.invert();
  80167. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  80168. var child = _a[_i];
  80169. var cm = child.getLocalMatrix();
  80170. cm.multiplyToRef(scaleMat, cm);
  80171. cm.m[12] *= x;
  80172. cm.m[13] *= y;
  80173. cm.m[14] *= z;
  80174. child._markAsDirtyAndDecompose();
  80175. }
  80176. this._markAsDirtyAndDecompose();
  80177. if (scaleChildren) {
  80178. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  80179. var child = _c[_b];
  80180. child.scale(x, y, z, scaleChildren);
  80181. }
  80182. }
  80183. };
  80184. /**
  80185. * Set the bone scaling in local space
  80186. * @param scale defines the scaling vector
  80187. */
  80188. Bone.prototype.setScale = function (scale) {
  80189. this._decompose();
  80190. this._localScaling.copyFrom(scale);
  80191. this._markAsDirtyAndCompose();
  80192. };
  80193. /**
  80194. * Gets the current scaling in local space
  80195. * @returns the current scaling vector
  80196. */
  80197. Bone.prototype.getScale = function () {
  80198. this._decompose();
  80199. return this._localScaling;
  80200. };
  80201. /**
  80202. * Gets the current scaling in local space and stores it in a target vector
  80203. * @param result defines the target vector
  80204. */
  80205. Bone.prototype.getScaleToRef = function (result) {
  80206. this._decompose();
  80207. result.copyFrom(this._localScaling);
  80208. };
  80209. /**
  80210. * Set the yaw, pitch, and roll of the bone in local or world space
  80211. * @param yaw The rotation of the bone on the y axis
  80212. * @param pitch The rotation of the bone on the x axis
  80213. * @param roll The rotation of the bone on the z axis
  80214. * @param space The space that the axes of rotation are in
  80215. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80216. */
  80217. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  80218. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80219. if (space === BABYLON.Space.LOCAL) {
  80220. var quat = Bone._tmpQuat;
  80221. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  80222. this.setRotationQuaternion(quat, space, mesh);
  80223. return;
  80224. }
  80225. var rotMatInv = Bone._tmpMats[0];
  80226. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80227. return;
  80228. }
  80229. var rotMat = Bone._tmpMats[1];
  80230. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  80231. rotMatInv.multiplyToRef(rotMat, rotMat);
  80232. this._rotateWithMatrix(rotMat, space, mesh);
  80233. };
  80234. /**
  80235. * Add a rotation to the bone on an axis in local or world space
  80236. * @param axis The axis to rotate the bone on
  80237. * @param amount The amount to rotate the bone
  80238. * @param space The space that the axis is in
  80239. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80240. */
  80241. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80243. var rmat = Bone._tmpMats[0];
  80244. rmat.m[12] = 0;
  80245. rmat.m[13] = 0;
  80246. rmat.m[14] = 0;
  80247. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80248. this._rotateWithMatrix(rmat, space, mesh);
  80249. };
  80250. /**
  80251. * Set the rotation of the bone to a particular axis angle in local or world space
  80252. * @param axis The axis to rotate the bone on
  80253. * @param angle The angle that the bone should be rotated to
  80254. * @param space The space that the axis is in
  80255. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80256. */
  80257. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80258. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80259. if (space === BABYLON.Space.LOCAL) {
  80260. var quat = Bone._tmpQuat;
  80261. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80262. this.setRotationQuaternion(quat, space, mesh);
  80263. return;
  80264. }
  80265. var rotMatInv = Bone._tmpMats[0];
  80266. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80267. return;
  80268. }
  80269. var rotMat = Bone._tmpMats[1];
  80270. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80271. rotMatInv.multiplyToRef(rotMat, rotMat);
  80272. this._rotateWithMatrix(rotMat, space, mesh);
  80273. };
  80274. /**
  80275. * Set the euler rotation of the bone in local of world space
  80276. * @param rotation The euler rotation that the bone should be set to
  80277. * @param space The space that the rotation is in
  80278. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80279. */
  80280. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80281. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80282. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80283. };
  80284. /**
  80285. * Set the quaternion rotation of the bone in local of world space
  80286. * @param quat The quaternion rotation that the bone should be set to
  80287. * @param space The space that the rotation is in
  80288. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80289. */
  80290. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80291. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80292. if (space === BABYLON.Space.LOCAL) {
  80293. this._decompose();
  80294. this._localRotation.copyFrom(quat);
  80295. this._markAsDirtyAndCompose();
  80296. return;
  80297. }
  80298. var rotMatInv = Bone._tmpMats[0];
  80299. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80300. return;
  80301. }
  80302. var rotMat = Bone._tmpMats[1];
  80303. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80304. rotMatInv.multiplyToRef(rotMat, rotMat);
  80305. this._rotateWithMatrix(rotMat, space, mesh);
  80306. };
  80307. /**
  80308. * Set the rotation matrix of the bone in local of world space
  80309. * @param rotMat The rotation matrix that the bone should be set to
  80310. * @param space The space that the rotation is in
  80311. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80312. */
  80313. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80314. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80315. if (space === BABYLON.Space.LOCAL) {
  80316. var quat = Bone._tmpQuat;
  80317. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80318. this.setRotationQuaternion(quat, space, mesh);
  80319. return;
  80320. }
  80321. var rotMatInv = Bone._tmpMats[0];
  80322. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80323. return;
  80324. }
  80325. var rotMat2 = Bone._tmpMats[1];
  80326. rotMat2.copyFrom(rotMat);
  80327. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80328. this._rotateWithMatrix(rotMat2, space, mesh);
  80329. };
  80330. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80331. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80332. var lmat = this.getLocalMatrix();
  80333. var lx = lmat.m[12];
  80334. var ly = lmat.m[13];
  80335. var lz = lmat.m[14];
  80336. var parent = this.getParent();
  80337. var parentScale = Bone._tmpMats[3];
  80338. var parentScaleInv = Bone._tmpMats[4];
  80339. if (parent && space == BABYLON.Space.WORLD) {
  80340. if (mesh) {
  80341. parentScale.copyFrom(mesh.getWorldMatrix());
  80342. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80343. }
  80344. else {
  80345. parentScale.copyFrom(parent.getAbsoluteTransform());
  80346. }
  80347. parentScaleInv.copyFrom(parentScale);
  80348. parentScaleInv.invert();
  80349. lmat.multiplyToRef(parentScale, lmat);
  80350. lmat.multiplyToRef(rmat, lmat);
  80351. lmat.multiplyToRef(parentScaleInv, lmat);
  80352. }
  80353. else {
  80354. if (space == BABYLON.Space.WORLD && mesh) {
  80355. parentScale.copyFrom(mesh.getWorldMatrix());
  80356. parentScaleInv.copyFrom(parentScale);
  80357. parentScaleInv.invert();
  80358. lmat.multiplyToRef(parentScale, lmat);
  80359. lmat.multiplyToRef(rmat, lmat);
  80360. lmat.multiplyToRef(parentScaleInv, lmat);
  80361. }
  80362. else {
  80363. lmat.multiplyToRef(rmat, lmat);
  80364. }
  80365. }
  80366. lmat.m[12] = lx;
  80367. lmat.m[13] = ly;
  80368. lmat.m[14] = lz;
  80369. this.computeAbsoluteTransforms();
  80370. this._markAsDirtyAndDecompose();
  80371. };
  80372. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80373. var scaleMatrix = Bone._tmpMats[2];
  80374. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80375. if (mesh) {
  80376. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80377. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80378. }
  80379. rotMatInv.invert();
  80380. if (isNaN(rotMatInv.m[0])) {
  80381. // Matrix failed to invert.
  80382. // This can happen if scale is zero for example.
  80383. return false;
  80384. }
  80385. scaleMatrix.m[0] *= this._scalingDeterminant;
  80386. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80387. return true;
  80388. };
  80389. /**
  80390. * Get the position of the bone in local or world space
  80391. * @param space The space that the returned position is in
  80392. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80393. * @returns The position of the bone
  80394. */
  80395. Bone.prototype.getPosition = function (space, mesh) {
  80396. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80397. if (mesh === void 0) { mesh = null; }
  80398. var pos = BABYLON.Vector3.Zero();
  80399. this.getPositionToRef(space, mesh, pos);
  80400. return pos;
  80401. };
  80402. /**
  80403. * Copy the position of the bone to a vector3 in local or world space
  80404. * @param space The space that the returned position is in
  80405. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80406. * @param result The vector3 to copy the position to
  80407. */
  80408. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80409. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80410. if (space == BABYLON.Space.LOCAL) {
  80411. var lm = this.getLocalMatrix();
  80412. result.x = lm.m[12];
  80413. result.y = lm.m[13];
  80414. result.z = lm.m[14];
  80415. }
  80416. else {
  80417. var wm = null;
  80418. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80419. if (mesh) {
  80420. wm = mesh.getWorldMatrix();
  80421. }
  80422. this._skeleton.computeAbsoluteTransforms();
  80423. var tmat = Bone._tmpMats[0];
  80424. if (mesh && wm) {
  80425. tmat.copyFrom(this.getAbsoluteTransform());
  80426. tmat.multiplyToRef(wm, tmat);
  80427. }
  80428. else {
  80429. tmat = this.getAbsoluteTransform();
  80430. }
  80431. result.x = tmat.m[12];
  80432. result.y = tmat.m[13];
  80433. result.z = tmat.m[14];
  80434. }
  80435. };
  80436. /**
  80437. * Get the absolute position of the bone (world space)
  80438. * @param mesh The mesh that this bone is attached to
  80439. * @returns The absolute position of the bone
  80440. */
  80441. Bone.prototype.getAbsolutePosition = function (mesh) {
  80442. if (mesh === void 0) { mesh = null; }
  80443. var pos = BABYLON.Vector3.Zero();
  80444. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80445. return pos;
  80446. };
  80447. /**
  80448. * Copy the absolute position of the bone (world space) to the result param
  80449. * @param mesh The mesh that this bone is attached to
  80450. * @param result The vector3 to copy the absolute position to
  80451. */
  80452. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80453. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80454. };
  80455. /**
  80456. * Compute the absolute transforms of this bone and its children
  80457. */
  80458. Bone.prototype.computeAbsoluteTransforms = function () {
  80459. this._compose();
  80460. if (this._parent) {
  80461. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80462. }
  80463. else {
  80464. this._absoluteTransform.copyFrom(this._localMatrix);
  80465. var poseMatrix = this._skeleton.getPoseMatrix();
  80466. if (poseMatrix) {
  80467. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80468. }
  80469. }
  80470. var children = this.children;
  80471. var len = children.length;
  80472. for (var i = 0; i < len; i++) {
  80473. children[i].computeAbsoluteTransforms();
  80474. }
  80475. };
  80476. /**
  80477. * Get the world direction from an axis that is in the local space of the bone
  80478. * @param localAxis The local direction that is used to compute the world direction
  80479. * @param mesh The mesh that this bone is attached to
  80480. * @returns The world direction
  80481. */
  80482. Bone.prototype.getDirection = function (localAxis, mesh) {
  80483. if (mesh === void 0) { mesh = null; }
  80484. var result = BABYLON.Vector3.Zero();
  80485. this.getDirectionToRef(localAxis, mesh, result);
  80486. return result;
  80487. };
  80488. /**
  80489. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80490. * @param localAxis The local direction that is used to compute the world direction
  80491. * @param mesh The mesh that this bone is attached to
  80492. * @param result The vector3 that the world direction will be copied to
  80493. */
  80494. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80495. if (mesh === void 0) { mesh = null; }
  80496. var wm = null;
  80497. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80498. if (mesh) {
  80499. wm = mesh.getWorldMatrix();
  80500. }
  80501. this._skeleton.computeAbsoluteTransforms();
  80502. var mat = Bone._tmpMats[0];
  80503. mat.copyFrom(this.getAbsoluteTransform());
  80504. if (mesh && wm) {
  80505. mat.multiplyToRef(wm, mat);
  80506. }
  80507. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80508. result.normalize();
  80509. };
  80510. /**
  80511. * Get the euler rotation of the bone in local or world space
  80512. * @param space The space that the rotation should be in
  80513. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80514. * @returns The euler rotation
  80515. */
  80516. Bone.prototype.getRotation = function (space, mesh) {
  80517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80518. if (mesh === void 0) { mesh = null; }
  80519. var result = BABYLON.Vector3.Zero();
  80520. this.getRotationToRef(space, mesh, result);
  80521. return result;
  80522. };
  80523. /**
  80524. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80525. * @param space The space that the rotation should be in
  80526. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80527. * @param result The vector3 that the rotation should be copied to
  80528. */
  80529. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80530. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80531. if (mesh === void 0) { mesh = null; }
  80532. var quat = Bone._tmpQuat;
  80533. this.getRotationQuaternionToRef(space, mesh, quat);
  80534. quat.toEulerAnglesToRef(result);
  80535. };
  80536. /**
  80537. * Get the quaternion rotation of the bone in either local or world space
  80538. * @param space The space that the rotation should be in
  80539. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80540. * @returns The quaternion rotation
  80541. */
  80542. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80543. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80544. if (mesh === void 0) { mesh = null; }
  80545. var result = BABYLON.Quaternion.Identity();
  80546. this.getRotationQuaternionToRef(space, mesh, result);
  80547. return result;
  80548. };
  80549. /**
  80550. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80551. * @param space The space that the rotation should be in
  80552. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80553. * @param result The quaternion that the rotation should be copied to
  80554. */
  80555. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80556. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80557. if (mesh === void 0) { mesh = null; }
  80558. if (space == BABYLON.Space.LOCAL) {
  80559. this._decompose();
  80560. result.copyFrom(this._localRotation);
  80561. }
  80562. else {
  80563. var mat = Bone._tmpMats[0];
  80564. var amat = this.getAbsoluteTransform();
  80565. if (mesh) {
  80566. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80567. }
  80568. else {
  80569. mat.copyFrom(amat);
  80570. }
  80571. mat.m[0] *= this._scalingDeterminant;
  80572. mat.m[1] *= this._scalingDeterminant;
  80573. mat.m[2] *= this._scalingDeterminant;
  80574. mat.decompose(undefined, result, undefined);
  80575. }
  80576. };
  80577. /**
  80578. * Get the rotation matrix of the bone in local or world space
  80579. * @param space The space that the rotation should be in
  80580. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80581. * @returns The rotation matrix
  80582. */
  80583. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80584. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80585. var result = BABYLON.Matrix.Identity();
  80586. this.getRotationMatrixToRef(space, mesh, result);
  80587. return result;
  80588. };
  80589. /**
  80590. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80591. * @param space The space that the rotation should be in
  80592. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80593. * @param result The quaternion that the rotation should be copied to
  80594. */
  80595. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80596. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80597. if (space == BABYLON.Space.LOCAL) {
  80598. this.getLocalMatrix().getRotationMatrixToRef(result);
  80599. }
  80600. else {
  80601. var mat = Bone._tmpMats[0];
  80602. var amat = this.getAbsoluteTransform();
  80603. if (mesh) {
  80604. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80605. }
  80606. else {
  80607. mat.copyFrom(amat);
  80608. }
  80609. mat.m[0] *= this._scalingDeterminant;
  80610. mat.m[1] *= this._scalingDeterminant;
  80611. mat.m[2] *= this._scalingDeterminant;
  80612. mat.getRotationMatrixToRef(result);
  80613. }
  80614. };
  80615. /**
  80616. * Get the world position of a point that is in the local space of the bone
  80617. * @param position The local position
  80618. * @param mesh The mesh that this bone is attached to
  80619. * @returns The world position
  80620. */
  80621. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80622. if (mesh === void 0) { mesh = null; }
  80623. var result = BABYLON.Vector3.Zero();
  80624. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80625. return result;
  80626. };
  80627. /**
  80628. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80629. * @param position The local position
  80630. * @param mesh The mesh that this bone is attached to
  80631. * @param result The vector3 that the world position should be copied to
  80632. */
  80633. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80634. if (mesh === void 0) { mesh = null; }
  80635. var wm = null;
  80636. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80637. if (mesh) {
  80638. wm = mesh.getWorldMatrix();
  80639. }
  80640. this._skeleton.computeAbsoluteTransforms();
  80641. var tmat = Bone._tmpMats[0];
  80642. if (mesh && wm) {
  80643. tmat.copyFrom(this.getAbsoluteTransform());
  80644. tmat.multiplyToRef(wm, tmat);
  80645. }
  80646. else {
  80647. tmat = this.getAbsoluteTransform();
  80648. }
  80649. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80650. };
  80651. /**
  80652. * Get the local position of a point that is in world space
  80653. * @param position The world position
  80654. * @param mesh The mesh that this bone is attached to
  80655. * @returns The local position
  80656. */
  80657. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80658. if (mesh === void 0) { mesh = null; }
  80659. var result = BABYLON.Vector3.Zero();
  80660. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80661. return result;
  80662. };
  80663. /**
  80664. * Get the local position of a point that is in world space and copy it to the result param
  80665. * @param position The world position
  80666. * @param mesh The mesh that this bone is attached to
  80667. * @param result The vector3 that the local position should be copied to
  80668. */
  80669. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80670. if (mesh === void 0) { mesh = null; }
  80671. var wm = null;
  80672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80673. if (mesh) {
  80674. wm = mesh.getWorldMatrix();
  80675. }
  80676. this._skeleton.computeAbsoluteTransforms();
  80677. var tmat = Bone._tmpMats[0];
  80678. tmat.copyFrom(this.getAbsoluteTransform());
  80679. if (mesh && wm) {
  80680. tmat.multiplyToRef(wm, tmat);
  80681. }
  80682. tmat.invert();
  80683. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80684. };
  80685. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80686. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80687. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80688. return Bone;
  80689. }(BABYLON.Node));
  80690. BABYLON.Bone = Bone;
  80691. })(BABYLON || (BABYLON = {}));
  80692. //# sourceMappingURL=babylon.bone.js.map
  80693. var BABYLON;
  80694. (function (BABYLON) {
  80695. /**
  80696. * Class used to apply inverse kinematics to bones
  80697. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80698. */
  80699. var BoneIKController = /** @class */ (function () {
  80700. /**
  80701. * Creates a new BoneIKController
  80702. * @param mesh defines the mesh to control
  80703. * @param bone defines the bone to control
  80704. * @param options defines options to set up the controller
  80705. */
  80706. function BoneIKController(mesh, bone, options) {
  80707. /**
  80708. * Gets or sets the target position
  80709. */
  80710. this.targetPosition = BABYLON.Vector3.Zero();
  80711. /**
  80712. * Gets or sets the pole target position
  80713. */
  80714. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80715. /**
  80716. * Gets or sets the pole target local offset
  80717. */
  80718. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80719. /**
  80720. * Gets or sets the pole angle
  80721. */
  80722. this.poleAngle = 0;
  80723. /**
  80724. * 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)
  80725. */
  80726. this.slerpAmount = 1;
  80727. this._bone1Quat = BABYLON.Quaternion.Identity();
  80728. this._bone1Mat = BABYLON.Matrix.Identity();
  80729. this._bone2Ang = Math.PI;
  80730. this._maxAngle = Math.PI;
  80731. this._rightHandedSystem = false;
  80732. this._bendAxis = BABYLON.Vector3.Right();
  80733. this._slerping = false;
  80734. this._adjustRoll = 0;
  80735. this._bone2 = bone;
  80736. this._bone1 = bone.getParent();
  80737. if (!this._bone1) {
  80738. return;
  80739. }
  80740. this.mesh = mesh;
  80741. var bonePos = bone.getPosition();
  80742. if (bone.getAbsoluteTransform().determinant() > 0) {
  80743. this._rightHandedSystem = true;
  80744. this._bendAxis.x = 0;
  80745. this._bendAxis.y = 0;
  80746. this._bendAxis.z = -1;
  80747. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80748. this._adjustRoll = Math.PI * .5;
  80749. this._bendAxis.z = 1;
  80750. }
  80751. }
  80752. if (this._bone1.length) {
  80753. var boneScale1 = this._bone1.getScale();
  80754. var boneScale2 = this._bone2.getScale();
  80755. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80756. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80757. }
  80758. else if (this._bone1.children[0]) {
  80759. mesh.computeWorldMatrix(true);
  80760. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80761. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80762. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80763. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80764. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80765. }
  80766. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80767. this.maxAngle = Math.PI;
  80768. if (options) {
  80769. if (options.targetMesh) {
  80770. this.targetMesh = options.targetMesh;
  80771. this.targetMesh.computeWorldMatrix(true);
  80772. }
  80773. if (options.poleTargetMesh) {
  80774. this.poleTargetMesh = options.poleTargetMesh;
  80775. this.poleTargetMesh.computeWorldMatrix(true);
  80776. }
  80777. else if (options.poleTargetBone) {
  80778. this.poleTargetBone = options.poleTargetBone;
  80779. }
  80780. else if (this._bone1.getParent()) {
  80781. this.poleTargetBone = this._bone1.getParent();
  80782. }
  80783. if (options.poleTargetLocalOffset) {
  80784. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80785. }
  80786. if (options.poleAngle) {
  80787. this.poleAngle = options.poleAngle;
  80788. }
  80789. if (options.bendAxis) {
  80790. this._bendAxis.copyFrom(options.bendAxis);
  80791. }
  80792. if (options.maxAngle) {
  80793. this.maxAngle = options.maxAngle;
  80794. }
  80795. if (options.slerpAmount) {
  80796. this.slerpAmount = options.slerpAmount;
  80797. }
  80798. }
  80799. }
  80800. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80801. /**
  80802. * Gets or sets maximum allowed angle
  80803. */
  80804. get: function () {
  80805. return this._maxAngle;
  80806. },
  80807. set: function (value) {
  80808. this._setMaxAngle(value);
  80809. },
  80810. enumerable: true,
  80811. configurable: true
  80812. });
  80813. BoneIKController.prototype._setMaxAngle = function (ang) {
  80814. if (ang < 0) {
  80815. ang = 0;
  80816. }
  80817. if (ang > Math.PI || ang == undefined) {
  80818. ang = Math.PI;
  80819. }
  80820. this._maxAngle = ang;
  80821. var a = this._bone1Length;
  80822. var b = this._bone2Length;
  80823. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80824. };
  80825. /**
  80826. * Force the controller to update the bones
  80827. */
  80828. BoneIKController.prototype.update = function () {
  80829. var bone1 = this._bone1;
  80830. if (!bone1) {
  80831. return;
  80832. }
  80833. var target = this.targetPosition;
  80834. var poleTarget = this.poleTargetPosition;
  80835. var mat1 = BoneIKController._tmpMats[0];
  80836. var mat2 = BoneIKController._tmpMats[1];
  80837. if (this.targetMesh) {
  80838. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80839. }
  80840. if (this.poleTargetBone) {
  80841. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80842. }
  80843. else if (this.poleTargetMesh) {
  80844. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80845. }
  80846. var bonePos = BoneIKController._tmpVecs[0];
  80847. var zaxis = BoneIKController._tmpVecs[1];
  80848. var xaxis = BoneIKController._tmpVecs[2];
  80849. var yaxis = BoneIKController._tmpVecs[3];
  80850. var upAxis = BoneIKController._tmpVecs[4];
  80851. var _tmpQuat = BoneIKController._tmpQuat;
  80852. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80853. poleTarget.subtractToRef(bonePos, upAxis);
  80854. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80855. upAxis.y = 1;
  80856. }
  80857. else {
  80858. upAxis.normalize();
  80859. }
  80860. target.subtractToRef(bonePos, yaxis);
  80861. yaxis.normalize();
  80862. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80863. zaxis.normalize();
  80864. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80865. xaxis.normalize();
  80866. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80867. var a = this._bone1Length;
  80868. var b = this._bone2Length;
  80869. var c = BABYLON.Vector3.Distance(bonePos, target);
  80870. if (this._maxReach > 0) {
  80871. c = Math.min(this._maxReach, c);
  80872. }
  80873. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80874. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80875. if (acosa > 1) {
  80876. acosa = 1;
  80877. }
  80878. if (acosb > 1) {
  80879. acosb = 1;
  80880. }
  80881. if (acosa < -1) {
  80882. acosa = -1;
  80883. }
  80884. if (acosb < -1) {
  80885. acosb = -1;
  80886. }
  80887. var angA = Math.acos(acosa);
  80888. var angB = Math.acos(acosb);
  80889. var angC = -angA - angB;
  80890. if (this._rightHandedSystem) {
  80891. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80892. mat2.multiplyToRef(mat1, mat1);
  80893. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80894. mat2.multiplyToRef(mat1, mat1);
  80895. }
  80896. else {
  80897. var _tmpVec = BoneIKController._tmpVecs[5];
  80898. _tmpVec.copyFrom(this._bendAxis);
  80899. _tmpVec.x *= -1;
  80900. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80901. mat2.multiplyToRef(mat1, mat1);
  80902. }
  80903. if (this.poleAngle) {
  80904. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80905. mat1.multiplyToRef(mat2, mat1);
  80906. }
  80907. if (this._bone1) {
  80908. if (this.slerpAmount < 1) {
  80909. if (!this._slerping) {
  80910. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80911. }
  80912. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80913. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80914. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80915. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80916. this._slerping = true;
  80917. }
  80918. else {
  80919. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80920. this._bone1Mat.copyFrom(mat1);
  80921. this._slerping = false;
  80922. }
  80923. }
  80924. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80925. this._bone2Ang = angC;
  80926. };
  80927. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80928. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80929. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80930. return BoneIKController;
  80931. }());
  80932. BABYLON.BoneIKController = BoneIKController;
  80933. })(BABYLON || (BABYLON = {}));
  80934. //# sourceMappingURL=babylon.boneIKController.js.map
  80935. var BABYLON;
  80936. (function (BABYLON) {
  80937. /**
  80938. * Class used to make a bone look toward a point in space
  80939. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80940. */
  80941. var BoneLookController = /** @class */ (function () {
  80942. /**
  80943. * Create a BoneLookController
  80944. * @param mesh the mesh that the bone belongs to
  80945. * @param bone the bone that will be looking to the target
  80946. * @param target the target Vector3 to look at
  80947. * @param settings optional settings:
  80948. * * maxYaw: the maximum angle the bone will yaw to
  80949. * * minYaw: the minimum angle the bone will yaw to
  80950. * * maxPitch: the maximum angle the bone will pitch to
  80951. * * minPitch: the minimum angle the bone will yaw to
  80952. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80953. * * upAxis: the up axis of the coordinate system
  80954. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80955. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80956. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80957. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80958. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80959. * * adjustRoll: used to make an adjustment to the roll of the bone
  80960. **/
  80961. function BoneLookController(mesh, bone, target, options) {
  80962. /**
  80963. * The up axis of the coordinate system that is used when the bone is rotated
  80964. */
  80965. this.upAxis = BABYLON.Vector3.Up();
  80966. /**
  80967. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80968. */
  80969. this.upAxisSpace = BABYLON.Space.LOCAL;
  80970. /**
  80971. * Used to make an adjustment to the yaw of the bone
  80972. */
  80973. this.adjustYaw = 0;
  80974. /**
  80975. * Used to make an adjustment to the pitch of the bone
  80976. */
  80977. this.adjustPitch = 0;
  80978. /**
  80979. * Used to make an adjustment to the roll of the bone
  80980. */
  80981. this.adjustRoll = 0;
  80982. /**
  80983. * 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)
  80984. */
  80985. this.slerpAmount = 1;
  80986. this._boneQuat = BABYLON.Quaternion.Identity();
  80987. this._slerping = false;
  80988. this._firstFrameSkipped = false;
  80989. this._fowardAxis = BABYLON.Vector3.Forward();
  80990. this.mesh = mesh;
  80991. this.bone = bone;
  80992. this.target = target;
  80993. if (options) {
  80994. if (options.adjustYaw) {
  80995. this.adjustYaw = options.adjustYaw;
  80996. }
  80997. if (options.adjustPitch) {
  80998. this.adjustPitch = options.adjustPitch;
  80999. }
  81000. if (options.adjustRoll) {
  81001. this.adjustRoll = options.adjustRoll;
  81002. }
  81003. if (options.maxYaw != null) {
  81004. this.maxYaw = options.maxYaw;
  81005. }
  81006. else {
  81007. this.maxYaw = Math.PI;
  81008. }
  81009. if (options.minYaw != null) {
  81010. this.minYaw = options.minYaw;
  81011. }
  81012. else {
  81013. this.minYaw = -Math.PI;
  81014. }
  81015. if (options.maxPitch != null) {
  81016. this.maxPitch = options.maxPitch;
  81017. }
  81018. else {
  81019. this.maxPitch = Math.PI;
  81020. }
  81021. if (options.minPitch != null) {
  81022. this.minPitch = options.minPitch;
  81023. }
  81024. else {
  81025. this.minPitch = -Math.PI;
  81026. }
  81027. if (options.slerpAmount != null) {
  81028. this.slerpAmount = options.slerpAmount;
  81029. }
  81030. if (options.upAxis != null) {
  81031. this.upAxis = options.upAxis;
  81032. }
  81033. if (options.upAxisSpace != null) {
  81034. this.upAxisSpace = options.upAxisSpace;
  81035. }
  81036. if (options.yawAxis != null || options.pitchAxis != null) {
  81037. var newYawAxis = BABYLON.Axis.Y;
  81038. var newPitchAxis = BABYLON.Axis.X;
  81039. if (options.yawAxis != null) {
  81040. newYawAxis = options.yawAxis.clone();
  81041. newYawAxis.normalize();
  81042. }
  81043. if (options.pitchAxis != null) {
  81044. newPitchAxis = options.pitchAxis.clone();
  81045. newPitchAxis.normalize();
  81046. }
  81047. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  81048. this._transformYawPitch = BABYLON.Matrix.Identity();
  81049. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  81050. this._transformYawPitchInv = this._transformYawPitch.clone();
  81051. this._transformYawPitch.invert();
  81052. }
  81053. }
  81054. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  81055. this.upAxisSpace = BABYLON.Space.LOCAL;
  81056. }
  81057. }
  81058. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  81059. /**
  81060. * Gets or sets the minimum yaw angle that the bone can look to
  81061. */
  81062. get: function () {
  81063. return this._minYaw;
  81064. },
  81065. set: function (value) {
  81066. this._minYaw = value;
  81067. this._minYawSin = Math.sin(value);
  81068. this._minYawCos = Math.cos(value);
  81069. if (this._maxYaw != null) {
  81070. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81071. this._yawRange = this._maxYaw - this._minYaw;
  81072. }
  81073. },
  81074. enumerable: true,
  81075. configurable: true
  81076. });
  81077. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  81078. /**
  81079. * Gets or sets the maximum yaw angle that the bone can look to
  81080. */
  81081. get: function () {
  81082. return this._maxYaw;
  81083. },
  81084. set: function (value) {
  81085. this._maxYaw = value;
  81086. this._maxYawSin = Math.sin(value);
  81087. this._maxYawCos = Math.cos(value);
  81088. if (this._minYaw != null) {
  81089. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  81090. this._yawRange = this._maxYaw - this._minYaw;
  81091. }
  81092. },
  81093. enumerable: true,
  81094. configurable: true
  81095. });
  81096. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  81097. /**
  81098. * Gets or sets the minimum pitch angle that the bone can look to
  81099. */
  81100. get: function () {
  81101. return this._minPitch;
  81102. },
  81103. set: function (value) {
  81104. this._minPitch = value;
  81105. this._minPitchTan = Math.tan(value);
  81106. },
  81107. enumerable: true,
  81108. configurable: true
  81109. });
  81110. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  81111. /**
  81112. * Gets or sets the maximum pitch angle that the bone can look to
  81113. */
  81114. get: function () {
  81115. return this._maxPitch;
  81116. },
  81117. set: function (value) {
  81118. this._maxPitch = value;
  81119. this._maxPitchTan = Math.tan(value);
  81120. },
  81121. enumerable: true,
  81122. configurable: true
  81123. });
  81124. /**
  81125. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  81126. */
  81127. BoneLookController.prototype.update = function () {
  81128. //skip the first frame when slerping so that the mesh rotation is correct
  81129. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  81130. this._firstFrameSkipped = true;
  81131. return;
  81132. }
  81133. var bone = this.bone;
  81134. var bonePos = BoneLookController._tmpVecs[0];
  81135. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  81136. var target = this.target;
  81137. var _tmpMat1 = BoneLookController._tmpMats[0];
  81138. var _tmpMat2 = BoneLookController._tmpMats[1];
  81139. var mesh = this.mesh;
  81140. var parentBone = bone.getParent();
  81141. var upAxis = BoneLookController._tmpVecs[1];
  81142. upAxis.copyFrom(this.upAxis);
  81143. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  81144. if (this._transformYawPitch) {
  81145. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  81146. }
  81147. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  81148. }
  81149. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  81150. mesh.getDirectionToRef(upAxis, upAxis);
  81151. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  81152. upAxis.normalize();
  81153. }
  81154. }
  81155. var checkYaw = false;
  81156. var checkPitch = false;
  81157. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  81158. checkYaw = true;
  81159. }
  81160. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  81161. checkPitch = true;
  81162. }
  81163. if (checkYaw || checkPitch) {
  81164. var spaceMat = BoneLookController._tmpMats[2];
  81165. var spaceMatInv = BoneLookController._tmpMats[3];
  81166. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  81167. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  81168. }
  81169. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  81170. spaceMat.copyFrom(mesh.getWorldMatrix());
  81171. }
  81172. else {
  81173. var forwardAxis = BoneLookController._tmpVecs[2];
  81174. forwardAxis.copyFrom(this._fowardAxis);
  81175. if (this._transformYawPitch) {
  81176. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  81177. }
  81178. if (parentBone) {
  81179. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  81180. }
  81181. else {
  81182. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  81183. }
  81184. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  81185. rightAxis.normalize();
  81186. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  81187. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  81188. }
  81189. spaceMat.invertToRef(spaceMatInv);
  81190. var xzlen = null;
  81191. if (checkPitch) {
  81192. var localTarget = BoneLookController._tmpVecs[3];
  81193. target.subtractToRef(bonePos, localTarget);
  81194. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81195. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81196. var pitch = Math.atan2(localTarget.y, xzlen);
  81197. var newPitch = pitch;
  81198. if (pitch > this._maxPitch) {
  81199. localTarget.y = this._maxPitchTan * xzlen;
  81200. newPitch = this._maxPitch;
  81201. }
  81202. else if (pitch < this._minPitch) {
  81203. localTarget.y = this._minPitchTan * xzlen;
  81204. newPitch = this._minPitch;
  81205. }
  81206. if (pitch != newPitch) {
  81207. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81208. localTarget.addInPlace(bonePos);
  81209. target = localTarget;
  81210. }
  81211. }
  81212. if (checkYaw) {
  81213. var localTarget = BoneLookController._tmpVecs[4];
  81214. target.subtractToRef(bonePos, localTarget);
  81215. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  81216. var yaw = Math.atan2(localTarget.x, localTarget.z);
  81217. var newYaw = yaw;
  81218. if (yaw > this._maxYaw || yaw < this._minYaw) {
  81219. if (xzlen == null) {
  81220. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81221. }
  81222. if (this._yawRange > Math.PI) {
  81223. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  81224. localTarget.z = this._maxYawCos * xzlen;
  81225. localTarget.x = this._maxYawSin * xzlen;
  81226. newYaw = this._maxYaw;
  81227. }
  81228. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  81229. localTarget.z = this._minYawCos * xzlen;
  81230. localTarget.x = this._minYawSin * xzlen;
  81231. newYaw = this._minYaw;
  81232. }
  81233. }
  81234. else {
  81235. if (yaw > this._maxYaw) {
  81236. localTarget.z = this._maxYawCos * xzlen;
  81237. localTarget.x = this._maxYawSin * xzlen;
  81238. newYaw = this._maxYaw;
  81239. }
  81240. else if (yaw < this._minYaw) {
  81241. localTarget.z = this._minYawCos * xzlen;
  81242. localTarget.x = this._minYawSin * xzlen;
  81243. newYaw = this._minYaw;
  81244. }
  81245. }
  81246. }
  81247. if (this._slerping && this._yawRange > Math.PI) {
  81248. //are we going to be crossing into the min/max region?
  81249. var boneFwd = BoneLookController._tmpVecs[8];
  81250. boneFwd.copyFrom(BABYLON.Axis.Z);
  81251. if (this._transformYawPitch) {
  81252. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81253. }
  81254. var boneRotMat = BoneLookController._tmpMats[4];
  81255. this._boneQuat.toRotationMatrix(boneRotMat);
  81256. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81257. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81258. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81259. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81260. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81261. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81262. if (angBtwTar > angBtwMidYaw) {
  81263. if (xzlen == null) {
  81264. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81265. }
  81266. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81267. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81268. if (angBtwMin < angBtwMax) {
  81269. newYaw = boneYaw + Math.PI * .75;
  81270. localTarget.z = Math.cos(newYaw) * xzlen;
  81271. localTarget.x = Math.sin(newYaw) * xzlen;
  81272. }
  81273. else {
  81274. newYaw = boneYaw - Math.PI * .75;
  81275. localTarget.z = Math.cos(newYaw) * xzlen;
  81276. localTarget.x = Math.sin(newYaw) * xzlen;
  81277. }
  81278. }
  81279. }
  81280. if (yaw != newYaw) {
  81281. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81282. localTarget.addInPlace(bonePos);
  81283. target = localTarget;
  81284. }
  81285. }
  81286. }
  81287. var zaxis = BoneLookController._tmpVecs[5];
  81288. var xaxis = BoneLookController._tmpVecs[6];
  81289. var yaxis = BoneLookController._tmpVecs[7];
  81290. var _tmpQuat = BoneLookController._tmpQuat;
  81291. target.subtractToRef(bonePos, zaxis);
  81292. zaxis.normalize();
  81293. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81294. xaxis.normalize();
  81295. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81296. yaxis.normalize();
  81297. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81298. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81299. return;
  81300. }
  81301. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81302. return;
  81303. }
  81304. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81305. return;
  81306. }
  81307. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81308. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81309. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81310. }
  81311. if (this.slerpAmount < 1) {
  81312. if (!this._slerping) {
  81313. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81314. }
  81315. if (this._transformYawPitch) {
  81316. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81317. }
  81318. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81319. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81320. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81321. this._slerping = true;
  81322. }
  81323. else {
  81324. if (this._transformYawPitch) {
  81325. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81326. }
  81327. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81328. this._slerping = false;
  81329. }
  81330. };
  81331. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81332. var angDiff = ang2 - ang1;
  81333. angDiff %= Math.PI * 2;
  81334. if (angDiff > Math.PI) {
  81335. angDiff -= Math.PI * 2;
  81336. }
  81337. else if (angDiff < -Math.PI) {
  81338. angDiff += Math.PI * 2;
  81339. }
  81340. return angDiff;
  81341. };
  81342. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81343. ang1 %= (2 * Math.PI);
  81344. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81345. ang2 %= (2 * Math.PI);
  81346. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81347. var ab = 0;
  81348. if (ang1 < ang2) {
  81349. ab = ang2 - ang1;
  81350. }
  81351. else {
  81352. ab = ang1 - ang2;
  81353. }
  81354. if (ab > Math.PI) {
  81355. ab = Math.PI * 2 - ab;
  81356. }
  81357. return ab;
  81358. };
  81359. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81360. ang %= (2 * Math.PI);
  81361. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81362. ang1 %= (2 * Math.PI);
  81363. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81364. ang2 %= (2 * Math.PI);
  81365. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81366. if (ang1 < ang2) {
  81367. if (ang > ang1 && ang < ang2) {
  81368. return true;
  81369. }
  81370. }
  81371. else {
  81372. if (ang > ang2 && ang < ang1) {
  81373. return true;
  81374. }
  81375. }
  81376. return false;
  81377. };
  81378. 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()];
  81379. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81380. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81381. return BoneLookController;
  81382. }());
  81383. BABYLON.BoneLookController = BoneLookController;
  81384. })(BABYLON || (BABYLON = {}));
  81385. //# sourceMappingURL=babylon.boneLookController.js.map
  81386. var BABYLON;
  81387. (function (BABYLON) {
  81388. /**
  81389. * Class used to handle skinning animations
  81390. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81391. */
  81392. var Skeleton = /** @class */ (function () {
  81393. /**
  81394. * Creates a new skeleton
  81395. * @param name defines the skeleton name
  81396. * @param id defines the skeleton Id
  81397. * @param scene defines the hosting scene
  81398. */
  81399. function Skeleton(
  81400. /** defines the skeleton name */
  81401. name,
  81402. /** defines the skeleton Id */
  81403. id, scene) {
  81404. this.name = name;
  81405. this.id = id;
  81406. /**
  81407. * Gets the list of child bones
  81408. */
  81409. this.bones = new Array();
  81410. /**
  81411. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81412. */
  81413. this.needInitialSkinMatrix = false;
  81414. this._isDirty = true;
  81415. this._meshesWithPoseMatrix = new Array();
  81416. this._identity = BABYLON.Matrix.Identity();
  81417. this._ranges = {};
  81418. this._lastAbsoluteTransformsUpdateId = -1;
  81419. /**
  81420. * Specifies if the skeleton should be serialized
  81421. */
  81422. this.doNotSerialize = false;
  81423. this._animationPropertiesOverride = null;
  81424. // Events
  81425. /**
  81426. * An observable triggered before computing the skeleton's matrices
  81427. */
  81428. this.onBeforeComputeObservable = new BABYLON.Observable();
  81429. this.bones = [];
  81430. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81431. scene.skeletons.push(this);
  81432. //make sure it will recalculate the matrix next time prepare is called.
  81433. this._isDirty = true;
  81434. }
  81435. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81436. /**
  81437. * Gets or sets the animation properties override
  81438. */
  81439. get: function () {
  81440. if (!this._animationPropertiesOverride) {
  81441. return this._scene.animationPropertiesOverride;
  81442. }
  81443. return this._animationPropertiesOverride;
  81444. },
  81445. set: function (value) {
  81446. this._animationPropertiesOverride = value;
  81447. },
  81448. enumerable: true,
  81449. configurable: true
  81450. });
  81451. // Members
  81452. /**
  81453. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81454. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81455. * @returns a Float32Array containing matrices data
  81456. */
  81457. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81458. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81459. return mesh._bonesTransformMatrices;
  81460. }
  81461. if (!this._transformMatrices) {
  81462. this.prepare();
  81463. }
  81464. return this._transformMatrices;
  81465. };
  81466. /**
  81467. * Gets the current hosting scene
  81468. * @returns a scene object
  81469. */
  81470. Skeleton.prototype.getScene = function () {
  81471. return this._scene;
  81472. };
  81473. // Methods
  81474. /**
  81475. * Gets a string representing the current skeleton data
  81476. * @param fullDetails defines a boolean indicating if we want a verbose version
  81477. * @returns a string representing the current skeleton data
  81478. */
  81479. Skeleton.prototype.toString = function (fullDetails) {
  81480. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81481. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81482. if (fullDetails) {
  81483. ret += ", Ranges: {";
  81484. var first = true;
  81485. for (var name_1 in this._ranges) {
  81486. if (first) {
  81487. ret += ", ";
  81488. first = false;
  81489. }
  81490. ret += name_1;
  81491. }
  81492. ret += "}";
  81493. }
  81494. return ret;
  81495. };
  81496. /**
  81497. * Get bone's index searching by name
  81498. * @param name defines bone's name to search for
  81499. * @return the indice of the bone. Returns -1 if not found
  81500. */
  81501. Skeleton.prototype.getBoneIndexByName = function (name) {
  81502. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81503. if (this.bones[boneIndex].name === name) {
  81504. return boneIndex;
  81505. }
  81506. }
  81507. return -1;
  81508. };
  81509. /**
  81510. * Creater a new animation range
  81511. * @param name defines the name of the range
  81512. * @param from defines the start key
  81513. * @param to defines the end key
  81514. */
  81515. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81516. // check name not already in use
  81517. if (!this._ranges[name]) {
  81518. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81519. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81520. if (this.bones[i].animations[0]) {
  81521. this.bones[i].animations[0].createRange(name, from, to);
  81522. }
  81523. }
  81524. }
  81525. };
  81526. /**
  81527. * Delete a specific animation range
  81528. * @param name defines the name of the range
  81529. * @param deleteFrames defines if frames must be removed as well
  81530. */
  81531. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81532. if (deleteFrames === void 0) { deleteFrames = true; }
  81533. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81534. if (this.bones[i].animations[0]) {
  81535. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81536. }
  81537. }
  81538. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81539. };
  81540. /**
  81541. * Gets a specific animation range
  81542. * @param name defines the name of the range to look for
  81543. * @returns the requested animation range or null if not found
  81544. */
  81545. Skeleton.prototype.getAnimationRange = function (name) {
  81546. return this._ranges[name];
  81547. };
  81548. /**
  81549. * Gets the list of all animation ranges defined on this skeleton
  81550. * @returns an array
  81551. */
  81552. Skeleton.prototype.getAnimationRanges = function () {
  81553. var animationRanges = [];
  81554. var name;
  81555. var i = 0;
  81556. for (name in this._ranges) {
  81557. animationRanges[i] = this._ranges[name];
  81558. i++;
  81559. }
  81560. return animationRanges;
  81561. };
  81562. /**
  81563. * Copy animation range from a source skeleton.
  81564. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81565. * @param source defines the source skeleton
  81566. * @param name defines the name of the range to copy
  81567. * @param rescaleAsRequired defines if rescaling must be applied if required
  81568. * @returns true if operation was successful
  81569. */
  81570. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81571. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81572. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81573. return false;
  81574. }
  81575. var ret = true;
  81576. var frameOffset = this._getHighestAnimationFrame() + 1;
  81577. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81578. var boneDict = {};
  81579. var sourceBones = source.bones;
  81580. var nBones;
  81581. var i;
  81582. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81583. boneDict[sourceBones[i].name] = sourceBones[i];
  81584. }
  81585. if (this.bones.length !== sourceBones.length) {
  81586. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81587. ret = false;
  81588. }
  81589. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81590. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81591. var boneName = this.bones[i].name;
  81592. var sourceBone = boneDict[boneName];
  81593. if (sourceBone) {
  81594. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81595. }
  81596. else {
  81597. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81598. ret = false;
  81599. }
  81600. }
  81601. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81602. var range = source.getAnimationRange(name);
  81603. if (range) {
  81604. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81605. }
  81606. return ret;
  81607. };
  81608. /**
  81609. * Forces the skeleton to go to rest pose
  81610. */
  81611. Skeleton.prototype.returnToRest = function () {
  81612. for (var index = 0; index < this.bones.length; index++) {
  81613. this.bones[index].returnToRest();
  81614. }
  81615. };
  81616. Skeleton.prototype._getHighestAnimationFrame = function () {
  81617. var ret = 0;
  81618. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81619. if (this.bones[i].animations[0]) {
  81620. var highest = this.bones[i].animations[0].getHighestFrame();
  81621. if (ret < highest) {
  81622. ret = highest;
  81623. }
  81624. }
  81625. }
  81626. return ret;
  81627. };
  81628. /**
  81629. * Begin a specific animation range
  81630. * @param name defines the name of the range to start
  81631. * @param loop defines if looping must be turned on (false by default)
  81632. * @param speedRatio defines the speed ratio to apply (1 by default)
  81633. * @param onAnimationEnd defines a callback which will be called when animation will end
  81634. * @returns a new animatable
  81635. */
  81636. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81637. var range = this.getAnimationRange(name);
  81638. if (!range) {
  81639. return null;
  81640. }
  81641. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81642. };
  81643. /** @hidden */
  81644. Skeleton.prototype._markAsDirty = function () {
  81645. this._isDirty = true;
  81646. };
  81647. /** @hidden */
  81648. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81649. this._meshesWithPoseMatrix.push(mesh);
  81650. };
  81651. /** @hidden */
  81652. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81653. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81654. if (index > -1) {
  81655. this._meshesWithPoseMatrix.splice(index, 1);
  81656. }
  81657. };
  81658. /** @hidden */
  81659. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81660. this.onBeforeComputeObservable.notifyObservers(this);
  81661. for (var index = 0; index < this.bones.length; index++) {
  81662. var bone = this.bones[index];
  81663. var parentBone = bone.getParent();
  81664. if (parentBone) {
  81665. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81666. }
  81667. else {
  81668. if (initialSkinMatrix) {
  81669. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81670. }
  81671. else {
  81672. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81673. }
  81674. }
  81675. if (bone._index !== -1) {
  81676. var mappedIndex = bone._index === null ? index : bone._index;
  81677. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81678. }
  81679. }
  81680. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81681. };
  81682. /**
  81683. * Build all resources required to render a skeleton
  81684. */
  81685. Skeleton.prototype.prepare = function () {
  81686. if (!this._isDirty) {
  81687. return;
  81688. }
  81689. if (this.needInitialSkinMatrix) {
  81690. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81691. var mesh = this._meshesWithPoseMatrix[index];
  81692. var poseMatrix = mesh.getPoseMatrix();
  81693. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81694. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81695. }
  81696. if (this._synchronizedWithMesh !== mesh) {
  81697. this._synchronizedWithMesh = mesh;
  81698. // Prepare bones
  81699. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81700. var bone = this.bones[boneIndex];
  81701. if (!bone.getParent()) {
  81702. var matrix = bone.getBaseMatrix();
  81703. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81704. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81705. }
  81706. }
  81707. }
  81708. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81709. }
  81710. }
  81711. else {
  81712. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81713. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81714. }
  81715. this._computeTransformMatrices(this._transformMatrices, null);
  81716. }
  81717. this._isDirty = false;
  81718. this._scene._activeBones.addCount(this.bones.length, false);
  81719. };
  81720. /**
  81721. * Gets the list of animatables currently running for this skeleton
  81722. * @returns an array of animatables
  81723. */
  81724. Skeleton.prototype.getAnimatables = function () {
  81725. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81726. this._animatables = [];
  81727. for (var index = 0; index < this.bones.length; index++) {
  81728. this._animatables.push(this.bones[index]);
  81729. }
  81730. }
  81731. return this._animatables;
  81732. };
  81733. /**
  81734. * Clone the current skeleton
  81735. * @param name defines the name of the new skeleton
  81736. * @param id defines the id of the enw skeleton
  81737. * @returns the new skeleton
  81738. */
  81739. Skeleton.prototype.clone = function (name, id) {
  81740. var result = new Skeleton(name, id || name, this._scene);
  81741. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81742. for (var index = 0; index < this.bones.length; index++) {
  81743. var source = this.bones[index];
  81744. var parentBone = null;
  81745. var parent_1 = source.getParent();
  81746. if (parent_1) {
  81747. var parentIndex = this.bones.indexOf(parent_1);
  81748. parentBone = result.bones[parentIndex];
  81749. }
  81750. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81751. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81752. }
  81753. if (this._ranges) {
  81754. result._ranges = {};
  81755. for (var rangeName in this._ranges) {
  81756. var range = this._ranges[rangeName];
  81757. if (range) {
  81758. result._ranges[rangeName] = range.clone();
  81759. }
  81760. }
  81761. }
  81762. this._isDirty = true;
  81763. return result;
  81764. };
  81765. /**
  81766. * Enable animation blending for this skeleton
  81767. * @param blendingSpeed defines the blending speed to apply
  81768. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81769. */
  81770. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81771. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81772. this.bones.forEach(function (bone) {
  81773. bone.animations.forEach(function (animation) {
  81774. animation.enableBlending = true;
  81775. animation.blendingSpeed = blendingSpeed;
  81776. });
  81777. });
  81778. };
  81779. /**
  81780. * Releases all resources associated with the current skeleton
  81781. */
  81782. Skeleton.prototype.dispose = function () {
  81783. this._meshesWithPoseMatrix = [];
  81784. // Animations
  81785. this.getScene().stopAnimation(this);
  81786. // Remove from scene
  81787. this.getScene().removeSkeleton(this);
  81788. };
  81789. /**
  81790. * Serialize the skeleton in a JSON object
  81791. * @returns a JSON object
  81792. */
  81793. Skeleton.prototype.serialize = function () {
  81794. var serializationObject = {};
  81795. serializationObject.name = this.name;
  81796. serializationObject.id = this.id;
  81797. if (this.dimensionsAtRest) {
  81798. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81799. }
  81800. serializationObject.bones = [];
  81801. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81802. for (var index = 0; index < this.bones.length; index++) {
  81803. var bone = this.bones[index];
  81804. var parent_2 = bone.getParent();
  81805. var serializedBone = {
  81806. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81807. name: bone.name,
  81808. matrix: bone.getBaseMatrix().toArray(),
  81809. rest: bone.getRestPose().toArray()
  81810. };
  81811. serializationObject.bones.push(serializedBone);
  81812. if (bone.length) {
  81813. serializedBone.length = bone.length;
  81814. }
  81815. if (bone.metadata) {
  81816. serializedBone.metadata = bone.metadata;
  81817. }
  81818. if (bone.animations && bone.animations.length > 0) {
  81819. serializedBone.animation = bone.animations[0].serialize();
  81820. }
  81821. serializationObject.ranges = [];
  81822. for (var name in this._ranges) {
  81823. var source = this._ranges[name];
  81824. if (!source) {
  81825. continue;
  81826. }
  81827. var range = {};
  81828. range.name = name;
  81829. range.from = source.from;
  81830. range.to = source.to;
  81831. serializationObject.ranges.push(range);
  81832. }
  81833. }
  81834. return serializationObject;
  81835. };
  81836. /**
  81837. * Creates a new skeleton from serialized data
  81838. * @param parsedSkeleton defines the serialized data
  81839. * @param scene defines the hosting scene
  81840. * @returns a new skeleton
  81841. */
  81842. Skeleton.Parse = function (parsedSkeleton, scene) {
  81843. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81844. if (parsedSkeleton.dimensionsAtRest) {
  81845. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81846. }
  81847. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81848. var index;
  81849. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81850. var parsedBone = parsedSkeleton.bones[index];
  81851. var parentBone = null;
  81852. if (parsedBone.parentBoneIndex > -1) {
  81853. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81854. }
  81855. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81856. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81857. if (parsedBone.length) {
  81858. bone.length = parsedBone.length;
  81859. }
  81860. if (parsedBone.metadata) {
  81861. bone.metadata = parsedBone.metadata;
  81862. }
  81863. if (parsedBone.animation) {
  81864. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81865. }
  81866. }
  81867. // placed after bones, so createAnimationRange can cascade down
  81868. if (parsedSkeleton.ranges) {
  81869. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81870. var data = parsedSkeleton.ranges[index];
  81871. skeleton.createAnimationRange(data.name, data.from, data.to);
  81872. }
  81873. }
  81874. return skeleton;
  81875. };
  81876. /**
  81877. * Compute all node absolute transforms
  81878. * @param forceUpdate defines if computation must be done even if cache is up to date
  81879. */
  81880. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81881. if (forceUpdate === void 0) { forceUpdate = false; }
  81882. var renderId = this._scene.getRenderId();
  81883. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81884. this.bones[0].computeAbsoluteTransforms();
  81885. this._lastAbsoluteTransformsUpdateId = renderId;
  81886. }
  81887. };
  81888. /**
  81889. * Gets the root pose matrix
  81890. * @returns a matrix
  81891. */
  81892. Skeleton.prototype.getPoseMatrix = function () {
  81893. var poseMatrix = null;
  81894. if (this._meshesWithPoseMatrix.length > 0) {
  81895. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81896. }
  81897. return poseMatrix;
  81898. };
  81899. /**
  81900. * Sorts bones per internal index
  81901. */
  81902. Skeleton.prototype.sortBones = function () {
  81903. var bones = new Array();
  81904. var visited = new Array(this.bones.length);
  81905. for (var index = 0; index < this.bones.length; index++) {
  81906. this._sortBones(index, bones, visited);
  81907. }
  81908. this.bones = bones;
  81909. };
  81910. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81911. if (visited[index]) {
  81912. return;
  81913. }
  81914. visited[index] = true;
  81915. var bone = this.bones[index];
  81916. if (bone._index === undefined) {
  81917. bone._index = index;
  81918. }
  81919. var parentBone = bone.getParent();
  81920. if (parentBone) {
  81921. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81922. }
  81923. bones.push(bone);
  81924. };
  81925. return Skeleton;
  81926. }());
  81927. BABYLON.Skeleton = Skeleton;
  81928. })(BABYLON || (BABYLON = {}));
  81929. //# sourceMappingURL=babylon.skeleton.js.map
  81930. var BABYLON;
  81931. (function (BABYLON) {
  81932. /**
  81933. * Class representing spherical polynomial coefficients to the 3rd degree
  81934. */
  81935. var SphericalPolynomial = /** @class */ (function () {
  81936. function SphericalPolynomial() {
  81937. /**
  81938. * The x coefficients of the spherical polynomial
  81939. */
  81940. this.x = BABYLON.Vector3.Zero();
  81941. /**
  81942. * The y coefficients of the spherical polynomial
  81943. */
  81944. this.y = BABYLON.Vector3.Zero();
  81945. /**
  81946. * The z coefficients of the spherical polynomial
  81947. */
  81948. this.z = BABYLON.Vector3.Zero();
  81949. /**
  81950. * The xx coefficients of the spherical polynomial
  81951. */
  81952. this.xx = BABYLON.Vector3.Zero();
  81953. /**
  81954. * The yy coefficients of the spherical polynomial
  81955. */
  81956. this.yy = BABYLON.Vector3.Zero();
  81957. /**
  81958. * The zz coefficients of the spherical polynomial
  81959. */
  81960. this.zz = BABYLON.Vector3.Zero();
  81961. /**
  81962. * The xy coefficients of the spherical polynomial
  81963. */
  81964. this.xy = BABYLON.Vector3.Zero();
  81965. /**
  81966. * The yz coefficients of the spherical polynomial
  81967. */
  81968. this.yz = BABYLON.Vector3.Zero();
  81969. /**
  81970. * The zx coefficients of the spherical polynomial
  81971. */
  81972. this.zx = BABYLON.Vector3.Zero();
  81973. }
  81974. /**
  81975. * Adds an ambient color to the spherical polynomial
  81976. * @param color the color to add
  81977. */
  81978. SphericalPolynomial.prototype.addAmbient = function (color) {
  81979. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81980. this.xx = this.xx.add(colorVector);
  81981. this.yy = this.yy.add(colorVector);
  81982. this.zz = this.zz.add(colorVector);
  81983. };
  81984. /**
  81985. * Scales the spherical polynomial by the given amount
  81986. * @param scale the amount to scale
  81987. */
  81988. SphericalPolynomial.prototype.scale = function (scale) {
  81989. this.x = this.x.scale(scale);
  81990. this.y = this.y.scale(scale);
  81991. this.z = this.z.scale(scale);
  81992. this.xx = this.xx.scale(scale);
  81993. this.yy = this.yy.scale(scale);
  81994. this.zz = this.zz.scale(scale);
  81995. this.yz = this.yz.scale(scale);
  81996. this.zx = this.zx.scale(scale);
  81997. this.xy = this.xy.scale(scale);
  81998. };
  81999. /**
  82000. * Gets the spherical polynomial from harmonics
  82001. * @param harmonics the spherical harmonics
  82002. * @returns the spherical polynomial
  82003. */
  82004. SphericalPolynomial.FromHarmonics = function (harmonics) {
  82005. var result = new SphericalPolynomial();
  82006. result.x = harmonics.l11.scale(1.02333);
  82007. result.y = harmonics.l1_1.scale(1.02333);
  82008. result.z = harmonics.l10.scale(1.02333);
  82009. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  82010. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  82011. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  82012. result.yz = harmonics.l2_1.scale(0.858086);
  82013. result.zx = harmonics.l21.scale(0.858086);
  82014. result.xy = harmonics.l2_2.scale(0.858086);
  82015. result.scale(1.0 / Math.PI);
  82016. return result;
  82017. };
  82018. /**
  82019. * Constructs a spherical polynomial from an array.
  82020. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  82021. * @returns the spherical polynomial
  82022. */
  82023. SphericalPolynomial.FromArray = function (data) {
  82024. var sp = new SphericalPolynomial();
  82025. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  82026. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  82027. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  82028. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  82029. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  82030. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  82031. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  82032. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  82033. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  82034. return sp;
  82035. };
  82036. return SphericalPolynomial;
  82037. }());
  82038. BABYLON.SphericalPolynomial = SphericalPolynomial;
  82039. /**
  82040. * Class representing spherical harmonics coefficients to the 3rd degree
  82041. */
  82042. var SphericalHarmonics = /** @class */ (function () {
  82043. function SphericalHarmonics() {
  82044. /**
  82045. * The l0,0 coefficients of the spherical harmonics
  82046. */
  82047. this.l00 = BABYLON.Vector3.Zero();
  82048. /**
  82049. * The l1,-1 coefficients of the spherical harmonics
  82050. */
  82051. this.l1_1 = BABYLON.Vector3.Zero();
  82052. /**
  82053. * The l1,0 coefficients of the spherical harmonics
  82054. */
  82055. this.l10 = BABYLON.Vector3.Zero();
  82056. /**
  82057. * The l1,1 coefficients of the spherical harmonics
  82058. */
  82059. this.l11 = BABYLON.Vector3.Zero();
  82060. /**
  82061. * The l2,-2 coefficients of the spherical harmonics
  82062. */
  82063. this.l2_2 = BABYLON.Vector3.Zero();
  82064. /**
  82065. * The l2,-1 coefficients of the spherical harmonics
  82066. */
  82067. this.l2_1 = BABYLON.Vector3.Zero();
  82068. /**
  82069. * The l2,0 coefficients of the spherical harmonics
  82070. */
  82071. this.l20 = BABYLON.Vector3.Zero();
  82072. /**
  82073. * The l2,1 coefficients of the spherical harmonics
  82074. */
  82075. this.l21 = BABYLON.Vector3.Zero();
  82076. /**
  82077. * The l2,2 coefficients of the spherical harmonics
  82078. */
  82079. this.lL22 = BABYLON.Vector3.Zero();
  82080. }
  82081. /**
  82082. * Adds a light to the spherical harmonics
  82083. * @param direction the direction of the light
  82084. * @param color the color of the light
  82085. * @param deltaSolidAngle the delta solid angle of the light
  82086. */
  82087. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  82088. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  82089. var c = colorVector.scale(deltaSolidAngle);
  82090. this.l00 = this.l00.add(c.scale(0.282095));
  82091. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  82092. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  82093. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  82094. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  82095. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  82096. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  82097. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  82098. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  82099. };
  82100. /**
  82101. * Scales the spherical harmonics by the given amount
  82102. * @param scale the amount to scale
  82103. */
  82104. SphericalHarmonics.prototype.scale = function (scale) {
  82105. this.l00 = this.l00.scale(scale);
  82106. this.l1_1 = this.l1_1.scale(scale);
  82107. this.l10 = this.l10.scale(scale);
  82108. this.l11 = this.l11.scale(scale);
  82109. this.l2_2 = this.l2_2.scale(scale);
  82110. this.l2_1 = this.l2_1.scale(scale);
  82111. this.l20 = this.l20.scale(scale);
  82112. this.l21 = this.l21.scale(scale);
  82113. this.lL22 = this.lL22.scale(scale);
  82114. };
  82115. /**
  82116. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  82117. *
  82118. * ```
  82119. * E_lm = A_l * L_lm
  82120. * ```
  82121. *
  82122. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  82123. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  82124. * the scaling factors are given in equation 9.
  82125. */
  82126. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  82127. // Constant (Band 0)
  82128. this.l00 = this.l00.scale(3.141593);
  82129. // Linear (Band 1)
  82130. this.l1_1 = this.l1_1.scale(2.094395);
  82131. this.l10 = this.l10.scale(2.094395);
  82132. this.l11 = this.l11.scale(2.094395);
  82133. // Quadratic (Band 2)
  82134. this.l2_2 = this.l2_2.scale(0.785398);
  82135. this.l2_1 = this.l2_1.scale(0.785398);
  82136. this.l20 = this.l20.scale(0.785398);
  82137. this.l21 = this.l21.scale(0.785398);
  82138. this.lL22 = this.lL22.scale(0.785398);
  82139. };
  82140. /**
  82141. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82142. *
  82143. * ```
  82144. * L = (1/pi) * E * rho
  82145. * ```
  82146. *
  82147. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82148. */
  82149. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  82150. this.scale(1.0 / Math.PI);
  82151. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82152. // (The pixel shader must apply albedo after texture fetches, etc).
  82153. };
  82154. /**
  82155. * Gets the spherical harmonics from polynomial
  82156. * @param polynomial the spherical polynomial
  82157. * @returns the spherical harmonics
  82158. */
  82159. SphericalHarmonics.FromPolynomial = function (polynomial) {
  82160. var result = new SphericalHarmonics();
  82161. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  82162. result.l1_1 = polynomial.y.scale(0.977204);
  82163. result.l10 = polynomial.z.scale(0.977204);
  82164. result.l11 = polynomial.x.scale(0.977204);
  82165. result.l2_2 = polynomial.xy.scale(1.16538);
  82166. result.l2_1 = polynomial.yz.scale(1.16538);
  82167. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  82168. result.l21 = polynomial.zx.scale(1.16538);
  82169. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  82170. result.scale(Math.PI);
  82171. return result;
  82172. };
  82173. /**
  82174. * Constructs a spherical harmonics from an array.
  82175. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  82176. * @returns the spherical harmonics
  82177. */
  82178. SphericalHarmonics.FromArray = function (data) {
  82179. var sh = new SphericalHarmonics();
  82180. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  82181. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  82182. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  82183. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  82184. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  82185. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  82186. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  82187. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  82188. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  82189. return sh;
  82190. };
  82191. return SphericalHarmonics;
  82192. }());
  82193. BABYLON.SphericalHarmonics = SphericalHarmonics;
  82194. })(BABYLON || (BABYLON = {}));
  82195. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  82196. var BABYLON;
  82197. (function (BABYLON) {
  82198. var FileFaceOrientation = /** @class */ (function () {
  82199. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  82200. this.name = name;
  82201. this.worldAxisForNormal = worldAxisForNormal;
  82202. this.worldAxisForFileX = worldAxisForFileX;
  82203. this.worldAxisForFileY = worldAxisForFileY;
  82204. }
  82205. return FileFaceOrientation;
  82206. }());
  82207. ;
  82208. /**
  82209. * Helper class dealing with the extraction of spherical polynomial dataArray
  82210. * from a cube map.
  82211. */
  82212. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  82213. function CubeMapToSphericalPolynomialTools() {
  82214. }
  82215. /**
  82216. * Converts a texture to the according Spherical Polynomial data.
  82217. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82218. *
  82219. * @param texture The texture to extract the information from.
  82220. * @return The Spherical Polynomial data.
  82221. */
  82222. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  82223. if (!texture.isCube) {
  82224. // Only supports cube Textures currently.
  82225. return null;
  82226. }
  82227. var size = texture.getSize().width;
  82228. var right = texture.readPixels(0);
  82229. var left = texture.readPixels(1);
  82230. var up;
  82231. var down;
  82232. if (texture.isRenderTarget) {
  82233. up = texture.readPixels(3);
  82234. down = texture.readPixels(2);
  82235. }
  82236. else {
  82237. up = texture.readPixels(2);
  82238. down = texture.readPixels(3);
  82239. }
  82240. var front = texture.readPixels(4);
  82241. var back = texture.readPixels(5);
  82242. var gammaSpace = texture.gammaSpace;
  82243. // Always read as RGBA.
  82244. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82245. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82246. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82247. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82248. }
  82249. var cubeInfo = {
  82250. size: size,
  82251. right: right,
  82252. left: left,
  82253. up: up,
  82254. down: down,
  82255. front: front,
  82256. back: back,
  82257. format: format,
  82258. type: type,
  82259. gammaSpace: gammaSpace,
  82260. };
  82261. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  82262. };
  82263. /**
  82264. * Converts a cubemap to the according Spherical Polynomial data.
  82265. * This extracts the first 3 orders only as they are the only one used in the lighting.
  82266. *
  82267. * @param cubeInfo The Cube map to extract the information from.
  82268. * @return The Spherical Polynomial data.
  82269. */
  82270. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  82271. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  82272. var totalSolidAngle = 0.0;
  82273. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  82274. var du = 2.0 / cubeInfo.size;
  82275. var dv = du;
  82276. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  82277. var minUV = du * 0.5 - 1.0;
  82278. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  82279. var fileFace = this.FileFaces[faceIndex];
  82280. var dataArray = cubeInfo[fileFace.name];
  82281. var v = minUV;
  82282. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  82283. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  82284. // Because SP is still linear, so summation is fine in that basis.
  82285. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  82286. for (var y = 0; y < cubeInfo.size; y++) {
  82287. var u = minUV;
  82288. for (var x = 0; x < cubeInfo.size; x++) {
  82289. // World direction (not normalised)
  82290. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  82291. worldDirection.normalize();
  82292. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  82293. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  82294. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  82295. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  82296. // Handle Integer types.
  82297. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  82298. r /= 255;
  82299. g /= 255;
  82300. b /= 255;
  82301. }
  82302. // Handle Gamma space textures.
  82303. if (cubeInfo.gammaSpace) {
  82304. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  82305. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  82306. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  82307. }
  82308. var color = new BABYLON.Color3(r, g, b);
  82309. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  82310. totalSolidAngle += deltaSolidAngle;
  82311. u += du;
  82312. }
  82313. v += dv;
  82314. }
  82315. }
  82316. // Solid angle for entire sphere is 4*pi
  82317. var sphereSolidAngle = 4.0 * Math.PI;
  82318. // Adjust the solid angle to allow for how many faces we processed.
  82319. var facesProcessed = 6.0;
  82320. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  82321. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  82322. // This is needed because the numerical integration over the cube uses a
  82323. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  82324. // and also to compensate for accumulative error due to float precision in the summation.
  82325. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  82326. sphericalHarmonics.scale(correctionFactor);
  82327. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  82328. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  82329. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  82330. };
  82331. CubeMapToSphericalPolynomialTools.FileFaces = [
  82332. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  82333. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  82334. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  82335. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  82336. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  82337. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  82338. ];
  82339. return CubeMapToSphericalPolynomialTools;
  82340. }());
  82341. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  82342. })(BABYLON || (BABYLON = {}));
  82343. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  82344. var BABYLON;
  82345. (function (BABYLON) {
  82346. /**
  82347. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  82348. */
  82349. var PanoramaToCubeMapTools = /** @class */ (function () {
  82350. function PanoramaToCubeMapTools() {
  82351. }
  82352. /**
  82353. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  82354. *
  82355. * @param float32Array The source data.
  82356. * @param inputWidth The width of the input panorama.
  82357. * @param inputhHeight The height of the input panorama.
  82358. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  82359. * @return The cubemap data
  82360. */
  82361. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  82362. if (!float32Array) {
  82363. throw "ConvertPanoramaToCubemap: input cannot be null";
  82364. }
  82365. if (float32Array.length != inputWidth * inputHeight * 3) {
  82366. throw "ConvertPanoramaToCubemap: input size is wrong";
  82367. }
  82368. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82369. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82370. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82371. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82372. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82373. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82374. return {
  82375. front: textureFront,
  82376. back: textureBack,
  82377. left: textureLeft,
  82378. right: textureRight,
  82379. up: textureUp,
  82380. down: textureDown,
  82381. size: size,
  82382. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82383. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82384. gammaSpace: false,
  82385. };
  82386. };
  82387. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82388. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82389. var textureArray = new Float32Array(buffer);
  82390. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82391. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82392. var dy = 1 / texSize;
  82393. var fy = 0;
  82394. for (var y = 0; y < texSize; y++) {
  82395. var xv1 = faceData[0];
  82396. var xv2 = faceData[2];
  82397. for (var x = 0; x < texSize; x++) {
  82398. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82399. v.normalize();
  82400. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82401. // 3 channels per pixels
  82402. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82403. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82404. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82405. xv1 = xv1.add(rotDX1);
  82406. xv2 = xv2.add(rotDX2);
  82407. }
  82408. fy += dy;
  82409. }
  82410. return textureArray;
  82411. };
  82412. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82413. var theta = Math.atan2(vDir.z, vDir.x);
  82414. var phi = Math.acos(vDir.y);
  82415. while (theta < -Math.PI)
  82416. theta += 2 * Math.PI;
  82417. while (theta > Math.PI)
  82418. theta -= 2 * Math.PI;
  82419. var dx = theta / Math.PI;
  82420. var dy = phi / Math.PI;
  82421. // recenter.
  82422. dx = dx * 0.5 + 0.5;
  82423. var px = Math.round(dx * inputWidth);
  82424. if (px < 0)
  82425. px = 0;
  82426. else if (px >= inputWidth)
  82427. px = inputWidth - 1;
  82428. var py = Math.round(dy * inputHeight);
  82429. if (py < 0)
  82430. py = 0;
  82431. else if (py >= inputHeight)
  82432. py = inputHeight - 1;
  82433. var inputY = (inputHeight - py - 1);
  82434. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82435. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82436. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82437. return {
  82438. r: r,
  82439. g: g,
  82440. b: b
  82441. };
  82442. };
  82443. PanoramaToCubeMapTools.FACE_FRONT = [
  82444. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82445. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82446. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82447. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82448. ];
  82449. PanoramaToCubeMapTools.FACE_BACK = [
  82450. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82451. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82452. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82453. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82454. ];
  82455. PanoramaToCubeMapTools.FACE_RIGHT = [
  82456. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82457. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82458. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82459. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82460. ];
  82461. PanoramaToCubeMapTools.FACE_LEFT = [
  82462. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82463. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82464. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82465. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82466. ];
  82467. PanoramaToCubeMapTools.FACE_DOWN = [
  82468. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82469. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82470. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82471. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82472. ];
  82473. PanoramaToCubeMapTools.FACE_UP = [
  82474. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82475. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82476. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82477. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82478. ];
  82479. return PanoramaToCubeMapTools;
  82480. }());
  82481. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82482. })(BABYLON || (BABYLON = {}));
  82483. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82484. var BABYLON;
  82485. (function (BABYLON) {
  82486. ;
  82487. /**
  82488. * This groups tools to convert HDR texture to native colors array.
  82489. */
  82490. var HDRTools = /** @class */ (function () {
  82491. function HDRTools() {
  82492. }
  82493. HDRTools.Ldexp = function (mantissa, exponent) {
  82494. if (exponent > 1023) {
  82495. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82496. }
  82497. if (exponent < -1074) {
  82498. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82499. }
  82500. return mantissa * Math.pow(2, exponent);
  82501. };
  82502. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82503. if (exponent > 0) { /*nonzero pixel*/
  82504. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82505. float32array[index + 0] = red * exponent;
  82506. float32array[index + 1] = green * exponent;
  82507. float32array[index + 2] = blue * exponent;
  82508. }
  82509. else {
  82510. float32array[index + 0] = 0;
  82511. float32array[index + 1] = 0;
  82512. float32array[index + 2] = 0;
  82513. }
  82514. };
  82515. HDRTools.readStringLine = function (uint8array, startIndex) {
  82516. var line = "";
  82517. var character = "";
  82518. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82519. character = String.fromCharCode(uint8array[i]);
  82520. if (character == "\n") {
  82521. break;
  82522. }
  82523. line += character;
  82524. }
  82525. return line;
  82526. };
  82527. /**
  82528. * Reads header information from an RGBE texture stored in a native array.
  82529. * More information on this format are available here:
  82530. * https://en.wikipedia.org/wiki/RGBE_image_format
  82531. *
  82532. * @param uint8array The binary file stored in native array.
  82533. * @return The header information.
  82534. */
  82535. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82536. var height = 0;
  82537. var width = 0;
  82538. var line = this.readStringLine(uint8array, 0);
  82539. if (line[0] != '#' || line[1] != '?') {
  82540. throw "Bad HDR Format.";
  82541. }
  82542. var endOfHeader = false;
  82543. var findFormat = false;
  82544. var lineIndex = 0;
  82545. do {
  82546. lineIndex += (line.length + 1);
  82547. line = this.readStringLine(uint8array, lineIndex);
  82548. if (line == "FORMAT=32-bit_rle_rgbe") {
  82549. findFormat = true;
  82550. }
  82551. else if (line.length == 0) {
  82552. endOfHeader = true;
  82553. }
  82554. } while (!endOfHeader);
  82555. if (!findFormat) {
  82556. throw "HDR Bad header format, unsupported FORMAT";
  82557. }
  82558. lineIndex += (line.length + 1);
  82559. line = this.readStringLine(uint8array, lineIndex);
  82560. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82561. var match = sizeRegexp.exec(line);
  82562. // TODO. Support +Y and -X if needed.
  82563. if (!match || match.length < 3) {
  82564. throw "HDR Bad header format, no size";
  82565. }
  82566. width = parseInt(match[2]);
  82567. height = parseInt(match[1]);
  82568. if (width < 8 || width > 0x7fff) {
  82569. throw "HDR Bad header format, unsupported size";
  82570. }
  82571. lineIndex += (line.length + 1);
  82572. return {
  82573. height: height,
  82574. width: width,
  82575. dataPosition: lineIndex
  82576. };
  82577. };
  82578. /**
  82579. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82580. * This RGBE texture needs to store the information as a panorama.
  82581. *
  82582. * More information on this format are available here:
  82583. * https://en.wikipedia.org/wiki/RGBE_image_format
  82584. *
  82585. * @param buffer The binary file stored in an array buffer.
  82586. * @param size The expected size of the extracted cubemap.
  82587. * @return The Cube Map information.
  82588. */
  82589. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82590. var uint8array = new Uint8Array(buffer);
  82591. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82592. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82593. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82594. return cubeMapData;
  82595. };
  82596. /**
  82597. * Returns the pixels data extracted from an RGBE texture.
  82598. * This pixels will be stored left to right up to down in the R G B order in one array.
  82599. *
  82600. * More information on this format are available here:
  82601. * https://en.wikipedia.org/wiki/RGBE_image_format
  82602. *
  82603. * @param uint8array The binary file stored in an array buffer.
  82604. * @param hdrInfo The header information of the file.
  82605. * @return The pixels data in RGB right to left up to down order.
  82606. */
  82607. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82608. // Keep for multi format supports.
  82609. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82610. };
  82611. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82612. var num_scanlines = hdrInfo.height;
  82613. var scanline_width = hdrInfo.width;
  82614. var a, b, c, d, count;
  82615. var dataIndex = hdrInfo.dataPosition;
  82616. var index = 0, endIndex = 0, i = 0;
  82617. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82618. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82619. // 3 channels of 4 bytes per pixel in float.
  82620. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82621. var resultArray = new Float32Array(resultBuffer);
  82622. // read in each successive scanline
  82623. while (num_scanlines > 0) {
  82624. a = uint8array[dataIndex++];
  82625. b = uint8array[dataIndex++];
  82626. c = uint8array[dataIndex++];
  82627. d = uint8array[dataIndex++];
  82628. if (a != 2 || b != 2 || (c & 0x80)) {
  82629. // this file is not run length encoded
  82630. throw "HDR Bad header format, not RLE";
  82631. }
  82632. if (((c << 8) | d) != scanline_width) {
  82633. throw "HDR Bad header format, wrong scan line width";
  82634. }
  82635. index = 0;
  82636. // read each of the four channels for the scanline into the buffer
  82637. for (i = 0; i < 4; i++) {
  82638. endIndex = (i + 1) * scanline_width;
  82639. while (index < endIndex) {
  82640. a = uint8array[dataIndex++];
  82641. b = uint8array[dataIndex++];
  82642. if (a > 128) {
  82643. // a run of the same value
  82644. count = a - 128;
  82645. if ((count == 0) || (count > endIndex - index)) {
  82646. throw "HDR Bad Format, bad scanline data (run)";
  82647. }
  82648. while (count-- > 0) {
  82649. scanLineArray[index++] = b;
  82650. }
  82651. }
  82652. else {
  82653. // a non-run
  82654. count = a;
  82655. if ((count == 0) || (count > endIndex - index)) {
  82656. throw "HDR Bad Format, bad scanline data (non-run)";
  82657. }
  82658. scanLineArray[index++] = b;
  82659. if (--count > 0) {
  82660. for (var j = 0; j < count; j++) {
  82661. scanLineArray[index++] = uint8array[dataIndex++];
  82662. }
  82663. }
  82664. }
  82665. }
  82666. }
  82667. // now convert data from buffer into floats
  82668. for (i = 0; i < scanline_width; i++) {
  82669. a = scanLineArray[i];
  82670. b = scanLineArray[i + scanline_width];
  82671. c = scanLineArray[i + 2 * scanline_width];
  82672. d = scanLineArray[i + 3 * scanline_width];
  82673. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82674. }
  82675. num_scanlines--;
  82676. }
  82677. return resultArray;
  82678. };
  82679. return HDRTools;
  82680. }());
  82681. BABYLON.HDRTools = HDRTools;
  82682. })(BABYLON || (BABYLON = {}));
  82683. //# sourceMappingURL=babylon.hdr.js.map
  82684. var BABYLON;
  82685. (function (BABYLON) {
  82686. /**
  82687. * Sets of helpers addressing the serialization and deserialization of environment texture
  82688. * stored in a BabylonJS env file.
  82689. * Those files are usually stored as .env files.
  82690. */
  82691. var EnvironmentTextureTools = /** @class */ (function () {
  82692. function EnvironmentTextureTools() {
  82693. }
  82694. /**
  82695. * Gets the environment info from an env file.
  82696. * @param data The array buffer containing the .env bytes.
  82697. * @returns the environment file info (the json header) if successfully parsed.
  82698. */
  82699. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82700. var dataView = new DataView(data);
  82701. var pos = 0;
  82702. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82703. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82704. BABYLON.Tools.Error('Not a babylon environment map');
  82705. return null;
  82706. }
  82707. }
  82708. // Read json manifest - collect characters up to null terminator
  82709. var manifestString = '';
  82710. var charCode = 0x00;
  82711. while ((charCode = dataView.getUint8(pos++))) {
  82712. manifestString += String.fromCharCode(charCode);
  82713. }
  82714. var manifest = JSON.parse(manifestString);
  82715. if (manifest.specular) {
  82716. // Extend the header with the position of the payload.
  82717. manifest.specular.specularDataPosition = pos;
  82718. }
  82719. return manifest;
  82720. };
  82721. /**
  82722. * Creates an environment texture from a loaded cube texture.
  82723. * @param texture defines the cube texture to convert in env file
  82724. * @return a promise containing the environment data if succesfull.
  82725. */
  82726. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82727. var _this = this;
  82728. var internalTexture = texture.getInternalTexture();
  82729. if (!internalTexture) {
  82730. return Promise.reject("The cube texture is invalid.");
  82731. }
  82732. if (!texture._prefiltered) {
  82733. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82734. }
  82735. var engine = internalTexture.getEngine();
  82736. if (engine && engine.premultipliedAlpha) {
  82737. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82738. }
  82739. var canvas = engine.getRenderingCanvas();
  82740. if (!canvas) {
  82741. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82742. }
  82743. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82744. if (!engine.getCaps().textureFloatRender) {
  82745. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82746. if (!engine.getCaps().textureHalfFloatRender) {
  82747. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82748. }
  82749. }
  82750. var cubeWidth = internalTexture.width;
  82751. var hostingScene = new BABYLON.Scene(engine);
  82752. var specularTextures = {};
  82753. var promises = [];
  82754. // Read and collect all mipmaps data from the cube.
  82755. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82756. mipmapsCount = Math.round(mipmapsCount);
  82757. var _loop_1 = function (i) {
  82758. var faceWidth = Math.pow(2, mipmapsCount - i);
  82759. var _loop_2 = function (face) {
  82760. var data = texture.readPixels(face, i);
  82761. // Creates a temp texture with the face data.
  82762. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82763. // And rgbdEncode them.
  82764. var promise = new Promise(function (resolve, reject) {
  82765. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  82766. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82767. rgbdPostProcess.onApply = function (effect) {
  82768. effect._bindTexture("textureSampler", tempTexture);
  82769. };
  82770. // As the process needs to happen on the main canvas, keep track of the current size
  82771. var currentW = engine.getRenderWidth();
  82772. var currentH = engine.getRenderHeight();
  82773. // Set the desired size for the texture
  82774. engine.setSize(faceWidth, faceWidth);
  82775. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82776. // Reading datas from WebGL
  82777. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82778. var fileReader = new FileReader();
  82779. fileReader.onload = function (event) {
  82780. var arrayBuffer = event.target.result;
  82781. specularTextures[i * 6 + face] = arrayBuffer;
  82782. resolve();
  82783. };
  82784. fileReader.readAsArrayBuffer(blob);
  82785. });
  82786. // Reapply the previous canvas size
  82787. engine.setSize(currentW, currentH);
  82788. });
  82789. });
  82790. promises.push(promise);
  82791. };
  82792. // All faces of the cube.
  82793. for (var face = 0; face < 6; face++) {
  82794. _loop_2(face);
  82795. }
  82796. };
  82797. for (var i = 0; i <= mipmapsCount; i++) {
  82798. _loop_1(i);
  82799. }
  82800. // Once all the textures haves been collected as RGBD stored in PNGs
  82801. return Promise.all(promises).then(function () {
  82802. // We can delete the hosting scene keeping track of all the creation objects
  82803. hostingScene.dispose();
  82804. // Creates the json header for the env texture
  82805. var info = {
  82806. version: 1,
  82807. width: cubeWidth,
  82808. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82809. specular: {
  82810. mipmaps: []
  82811. }
  82812. };
  82813. // Sets the specular image data information
  82814. var position = 0;
  82815. for (var i = 0; i <= mipmapsCount; i++) {
  82816. for (var face = 0; face < 6; face++) {
  82817. var byteLength = specularTextures[i * 6 + face].byteLength;
  82818. info.specular.mipmaps.push({
  82819. length: byteLength,
  82820. position: position
  82821. });
  82822. position += byteLength;
  82823. }
  82824. }
  82825. // Encode the JSON as an array buffer
  82826. var infoString = JSON.stringify(info);
  82827. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82828. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82829. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82830. infoView[i] = infoString.charCodeAt(i);
  82831. }
  82832. // Ends up with a null terminator for easier parsing
  82833. infoView[infoString.length] = 0x00;
  82834. // Computes the final required size and creates the storage
  82835. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82836. var finalBuffer = new ArrayBuffer(totalSize);
  82837. var finalBufferView = new Uint8Array(finalBuffer);
  82838. var dataView = new DataView(finalBuffer);
  82839. // Copy the magic bytes identifying the file in
  82840. var pos = 0;
  82841. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82842. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82843. }
  82844. // Add the json info
  82845. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82846. pos += infoBuffer.byteLength;
  82847. // Finally inserts the texture data
  82848. for (var i = 0; i <= mipmapsCount; i++) {
  82849. for (var face = 0; face < 6; face++) {
  82850. var dataBuffer = specularTextures[i * 6 + face];
  82851. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82852. pos += dataBuffer.byteLength;
  82853. }
  82854. }
  82855. // Voila
  82856. return finalBuffer;
  82857. });
  82858. };
  82859. /**
  82860. * Creates a JSON representation of the spherical data.
  82861. * @param texture defines the texture containing the polynomials
  82862. * @return the JSON representation of the spherical info
  82863. */
  82864. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82865. var polynmials = texture.sphericalPolynomial;
  82866. if (polynmials == null) {
  82867. return null;
  82868. }
  82869. return {
  82870. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82871. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82872. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82873. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82874. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82875. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82876. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82877. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82878. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82879. };
  82880. };
  82881. /**
  82882. * Uploads the texture info contained in the env file to the GPU.
  82883. * @param texture defines the internal texture to upload to
  82884. * @param arrayBuffer defines the buffer cotaining the data to load
  82885. * @param info defines the texture info retrieved through the GetEnvInfo method
  82886. * @returns a promise
  82887. */
  82888. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  82889. if (info.version !== 1) {
  82890. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82891. }
  82892. var specularInfo = info.specular;
  82893. if (!specularInfo) {
  82894. // Nothing else parsed so far
  82895. return Promise.resolve();
  82896. }
  82897. // Double checks the enclosed info
  82898. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82899. mipmapsCount = Math.round(mipmapsCount) + 1;
  82900. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82901. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82902. }
  82903. var imageData = new Array(mipmapsCount);
  82904. for (var i = 0; i < mipmapsCount; i++) {
  82905. imageData[i] = new Array(6);
  82906. for (var face = 0; face < 6; face++) {
  82907. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  82908. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  82909. }
  82910. }
  82911. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  82912. };
  82913. /**
  82914. * Uploads the levels of image data to the GPU.
  82915. * @param texture defines the internal texture to upload to
  82916. * @param imageData defines the array buffer views of image data [mipmap][face]
  82917. * @returns a promise
  82918. */
  82919. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  82920. var mipmapsCount = imageData.length;
  82921. // Gets everything ready.
  82922. var engine = texture.getEngine();
  82923. var expandTexture = false;
  82924. var generateNonLODTextures = false;
  82925. var rgbdPostProcess = null;
  82926. var cubeRtt = null;
  82927. var lodTextures = null;
  82928. var caps = engine.getCaps();
  82929. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82930. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82931. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82932. // Add extra process if texture lod is not supported
  82933. if (!caps.textureLOD) {
  82934. expandTexture = false;
  82935. generateNonLODTextures = true;
  82936. lodTextures = {};
  82937. }
  82938. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82939. else if (engine.webGLVersion < 2) {
  82940. expandTexture = false;
  82941. }
  82942. // If half float available we can uncompress the texture
  82943. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82944. expandTexture = true;
  82945. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82946. }
  82947. // If full float available we can uncompress the texture
  82948. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82949. expandTexture = true;
  82950. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82951. }
  82952. // Expand the texture if possible
  82953. if (expandTexture) {
  82954. // Simply run through the decode PP
  82955. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82956. texture._isRGBD = false;
  82957. texture.invertY = false;
  82958. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82959. generateDepthBuffer: false,
  82960. generateMipMaps: true,
  82961. generateStencilBuffer: false,
  82962. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82963. type: texture.type,
  82964. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82965. });
  82966. }
  82967. else {
  82968. texture._isRGBD = true;
  82969. texture.invertY = true;
  82970. // In case of missing support, applies the same patch than DDS files.
  82971. if (generateNonLODTextures) {
  82972. var mipSlices = 3;
  82973. var scale = texture._lodGenerationScale;
  82974. var offset = texture._lodGenerationOffset;
  82975. for (var i = 0; i < mipSlices; i++) {
  82976. //compute LOD from even spacing in smoothness (matching shader calculation)
  82977. var smoothness = i / (mipSlices - 1);
  82978. var roughness = 1 - smoothness;
  82979. var minLODIndex = offset; // roughness = 0
  82980. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  82981. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82982. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82983. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82984. glTextureFromLod.isCube = true;
  82985. glTextureFromLod.invertY = true;
  82986. glTextureFromLod.generateMipMaps = false;
  82987. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82988. // Wrap in a base texture for easy binding.
  82989. var lodTexture = new BABYLON.BaseTexture(null);
  82990. lodTexture.isCube = true;
  82991. lodTexture._texture = glTextureFromLod;
  82992. lodTextures[mipmapIndex] = lodTexture;
  82993. switch (i) {
  82994. case 0:
  82995. texture._lodTextureLow = lodTexture;
  82996. break;
  82997. case 1:
  82998. texture._lodTextureMid = lodTexture;
  82999. break;
  83000. case 2:
  83001. texture._lodTextureHigh = lodTexture;
  83002. break;
  83003. }
  83004. }
  83005. }
  83006. }
  83007. var promises = [];
  83008. var _loop_3 = function (i) {
  83009. var _loop_4 = function (face) {
  83010. // Constructs an image element from image data
  83011. var bytes = imageData[i][face];
  83012. var blob = new Blob([bytes], { type: 'image/png' });
  83013. var url = URL.createObjectURL(blob);
  83014. var image = new Image();
  83015. image.src = url;
  83016. // Enqueue promise to upload to the texture.
  83017. var promise = new Promise(function (resolve, reject) {
  83018. image.onload = function () {
  83019. if (expandTexture) {
  83020. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  83021. reject(message);
  83022. }, image);
  83023. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  83024. // Uncompress the data to a RTT
  83025. rgbdPostProcess.onApply = function (effect) {
  83026. effect._bindTexture("textureSampler", tempTexture_1);
  83027. effect.setFloat2("scale", 1, 1);
  83028. };
  83029. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  83030. // Cleanup
  83031. engine.restoreDefaultFramebuffer();
  83032. tempTexture_1.dispose();
  83033. window.URL.revokeObjectURL(url);
  83034. resolve();
  83035. });
  83036. }
  83037. else {
  83038. engine._uploadImageToTexture(texture, face, i, image);
  83039. // Upload the face to the none lod texture support
  83040. if (generateNonLODTextures) {
  83041. var lodTexture = lodTextures[i];
  83042. if (lodTexture) {
  83043. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  83044. }
  83045. }
  83046. resolve();
  83047. }
  83048. };
  83049. image.onerror = function (error) {
  83050. reject(error);
  83051. };
  83052. });
  83053. promises.push(promise);
  83054. };
  83055. // All faces
  83056. for (var face = 0; face < 6; face++) {
  83057. _loop_4(face);
  83058. }
  83059. };
  83060. // All mipmaps
  83061. for (var i = 0; i < mipmapsCount; i++) {
  83062. _loop_3(i);
  83063. }
  83064. // Once all done, finishes the cleanup and return
  83065. return Promise.all(promises).then(function () {
  83066. // Relase temp RTT.
  83067. if (cubeRtt) {
  83068. engine._releaseFramebufferObjects(cubeRtt);
  83069. cubeRtt._swapAndDie(texture);
  83070. }
  83071. // Relase temp Post Process.
  83072. if (rgbdPostProcess) {
  83073. rgbdPostProcess.dispose();
  83074. }
  83075. // Flag internal texture as ready in case they are in use.
  83076. if (generateNonLODTextures) {
  83077. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  83078. texture._lodTextureHigh._texture.isReady = true;
  83079. }
  83080. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  83081. texture._lodTextureMid._texture.isReady = true;
  83082. }
  83083. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  83084. texture._lodTextureLow._texture.isReady = true;
  83085. }
  83086. }
  83087. });
  83088. };
  83089. /**
  83090. * Uploads spherical polynomials information to the texture.
  83091. * @param texture defines the texture we are trying to upload the information to
  83092. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  83093. */
  83094. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  83095. if (info.version !== 1) {
  83096. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  83097. }
  83098. var irradianceInfo = info.irradiance;
  83099. if (!irradianceInfo) {
  83100. return;
  83101. }
  83102. var sp = new BABYLON.SphericalPolynomial();
  83103. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  83104. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  83105. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  83106. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  83107. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  83108. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  83109. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  83110. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  83111. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  83112. texture._sphericalPolynomial = sp;
  83113. };
  83114. /**
  83115. * Magic number identifying the env file.
  83116. */
  83117. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  83118. return EnvironmentTextureTools;
  83119. }());
  83120. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  83121. })(BABYLON || (BABYLON = {}));
  83122. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  83123. var BABYLON;
  83124. (function (BABYLON) {
  83125. /**
  83126. * This represents a texture coming from an HDR input.
  83127. *
  83128. * The only supported format is currently panorama picture stored in RGBE format.
  83129. * Example of such files can be found on HDRLib: http://hdrlib.com/
  83130. */
  83131. var HDRCubeTexture = /** @class */ (function (_super) {
  83132. __extends(HDRCubeTexture, _super);
  83133. /**
  83134. * Instantiates an HDRTexture from the following parameters.
  83135. *
  83136. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  83137. * @param scene The scene the texture will be used in
  83138. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  83139. * @param noMipmap Forces to not generate the mipmap if true
  83140. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  83141. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  83142. * @param reserved Reserved flag for internal use.
  83143. */
  83144. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  83145. if (noMipmap === void 0) { noMipmap = false; }
  83146. if (generateHarmonics === void 0) { generateHarmonics = true; }
  83147. if (gammaSpace === void 0) { gammaSpace = false; }
  83148. if (reserved === void 0) { reserved = false; }
  83149. if (onLoad === void 0) { onLoad = null; }
  83150. if (onError === void 0) { onError = null; }
  83151. var _this = _super.call(this, scene) || this;
  83152. _this._generateHarmonics = true;
  83153. _this._onLoad = null;
  83154. _this._onError = null;
  83155. /**
  83156. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  83157. */
  83158. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  83159. _this._isBlocking = true;
  83160. _this._rotationY = 0;
  83161. /**
  83162. * Gets or sets the center of the bounding box associated with the cube texture
  83163. * It must define where the camera used to render the texture was set
  83164. */
  83165. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  83166. if (!url) {
  83167. return _this;
  83168. }
  83169. _this.name = url;
  83170. _this.url = url;
  83171. _this.hasAlpha = false;
  83172. _this.isCube = true;
  83173. _this._textureMatrix = BABYLON.Matrix.Identity();
  83174. _this._onLoad = onLoad;
  83175. _this._onError = onError;
  83176. _this.gammaSpace = gammaSpace;
  83177. _this._noMipmap = noMipmap;
  83178. _this._size = size;
  83179. _this._texture = _this._getFromCache(url, _this._noMipmap);
  83180. if (!_this._texture) {
  83181. if (!scene.useDelayedTextureLoading) {
  83182. _this.loadTexture();
  83183. }
  83184. else {
  83185. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  83186. }
  83187. }
  83188. return _this;
  83189. }
  83190. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  83191. /**
  83192. * Gets wether or not the texture is blocking during loading.
  83193. */
  83194. get: function () {
  83195. return this._isBlocking;
  83196. },
  83197. /**
  83198. * Sets wether or not the texture is blocking during loading.
  83199. */
  83200. set: function (value) {
  83201. this._isBlocking = value;
  83202. },
  83203. enumerable: true,
  83204. configurable: true
  83205. });
  83206. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  83207. /**
  83208. * Gets texture matrix rotation angle around Y axis radians.
  83209. */
  83210. get: function () {
  83211. return this._rotationY;
  83212. },
  83213. /**
  83214. * Sets texture matrix rotation angle around Y axis in radians.
  83215. */
  83216. set: function (value) {
  83217. this._rotationY = value;
  83218. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  83219. },
  83220. enumerable: true,
  83221. configurable: true
  83222. });
  83223. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  83224. get: function () {
  83225. return this._boundingBoxSize;
  83226. },
  83227. /**
  83228. * Gets or sets the size of the bounding box associated with the cube texture
  83229. * When defined, the cubemap will switch to local mode
  83230. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  83231. * @example https://www.babylonjs-playground.com/#RNASML
  83232. */
  83233. set: function (value) {
  83234. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  83235. return;
  83236. }
  83237. this._boundingBoxSize = value;
  83238. var scene = this.getScene();
  83239. if (scene) {
  83240. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  83241. }
  83242. },
  83243. enumerable: true,
  83244. configurable: true
  83245. });
  83246. /**
  83247. * Occurs when the file is raw .hdr file.
  83248. */
  83249. HDRCubeTexture.prototype.loadTexture = function () {
  83250. var _this = this;
  83251. var callback = function (buffer) {
  83252. _this.lodGenerationOffset = 0.0;
  83253. _this.lodGenerationScale = 0.8;
  83254. var scene = _this.getScene();
  83255. if (!scene) {
  83256. return null;
  83257. }
  83258. // Extract the raw linear data.
  83259. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  83260. // Generate harmonics if needed.
  83261. if (_this._generateHarmonics) {
  83262. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  83263. _this.sphericalPolynomial = sphericalPolynomial;
  83264. }
  83265. var results = [];
  83266. var byteArray = null;
  83267. // Push each faces.
  83268. for (var j = 0; j < 6; j++) {
  83269. // Create uintarray fallback.
  83270. if (!scene.getEngine().getCaps().textureFloat) {
  83271. // 3 channels of 1 bytes per pixel in bytes.
  83272. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83273. byteArray = new Uint8Array(byteBuffer);
  83274. }
  83275. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83276. // If special cases.
  83277. if (_this.gammaSpace || byteArray) {
  83278. for (var i = 0; i < _this._size * _this._size; i++) {
  83279. // Put in gamma space if requested.
  83280. if (_this.gammaSpace) {
  83281. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83282. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83283. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83284. }
  83285. // Convert to int texture for fallback.
  83286. if (byteArray) {
  83287. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83288. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83289. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83290. // May use luminance instead if the result is not accurate.
  83291. var max = Math.max(Math.max(r, g), b);
  83292. if (max > 255) {
  83293. var scale = 255 / max;
  83294. r *= scale;
  83295. g *= scale;
  83296. b *= scale;
  83297. }
  83298. byteArray[(i * 3) + 0] = r;
  83299. byteArray[(i * 3) + 1] = g;
  83300. byteArray[(i * 3) + 2] = b;
  83301. }
  83302. }
  83303. }
  83304. if (byteArray) {
  83305. results.push(byteArray);
  83306. }
  83307. else {
  83308. results.push(dataFace);
  83309. }
  83310. }
  83311. return results;
  83312. };
  83313. var scene = this.getScene();
  83314. if (scene) {
  83315. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  83316. }
  83317. };
  83318. HDRCubeTexture.prototype.clone = function () {
  83319. var scene = this.getScene();
  83320. if (!scene) {
  83321. return this;
  83322. }
  83323. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83324. // Base texture
  83325. newTexture.level = this.level;
  83326. newTexture.wrapU = this.wrapU;
  83327. newTexture.wrapV = this.wrapV;
  83328. newTexture.coordinatesIndex = this.coordinatesIndex;
  83329. newTexture.coordinatesMode = this.coordinatesMode;
  83330. return newTexture;
  83331. };
  83332. // Methods
  83333. HDRCubeTexture.prototype.delayLoad = function () {
  83334. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83335. return;
  83336. }
  83337. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83338. this._texture = this._getFromCache(this.url, this._noMipmap);
  83339. if (!this._texture) {
  83340. this.loadTexture();
  83341. }
  83342. };
  83343. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83344. return this._textureMatrix;
  83345. };
  83346. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83347. this._textureMatrix = value;
  83348. };
  83349. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83350. var texture = null;
  83351. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83352. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83353. texture.name = parsedTexture.name;
  83354. texture.hasAlpha = parsedTexture.hasAlpha;
  83355. texture.level = parsedTexture.level;
  83356. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83357. texture.isBlocking = parsedTexture.isBlocking;
  83358. }
  83359. if (texture) {
  83360. if (parsedTexture.boundingBoxPosition) {
  83361. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83362. }
  83363. if (parsedTexture.boundingBoxSize) {
  83364. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83365. }
  83366. if (parsedTexture.rotationY) {
  83367. texture.rotationY = parsedTexture.rotationY;
  83368. }
  83369. }
  83370. return texture;
  83371. };
  83372. HDRCubeTexture.prototype.serialize = function () {
  83373. if (!this.name) {
  83374. return null;
  83375. }
  83376. var serializationObject = {};
  83377. serializationObject.name = this.name;
  83378. serializationObject.hasAlpha = this.hasAlpha;
  83379. serializationObject.isCube = true;
  83380. serializationObject.level = this.level;
  83381. serializationObject.size = this._size;
  83382. serializationObject.coordinatesMode = this.coordinatesMode;
  83383. serializationObject.useInGammaSpace = this.gammaSpace;
  83384. serializationObject.generateHarmonics = this._generateHarmonics;
  83385. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83386. serializationObject.noMipmap = this._noMipmap;
  83387. serializationObject.isBlocking = this._isBlocking;
  83388. serializationObject.rotationY = this._rotationY;
  83389. return serializationObject;
  83390. };
  83391. HDRCubeTexture._facesMapping = [
  83392. "right",
  83393. "left",
  83394. "up",
  83395. "down",
  83396. "front",
  83397. "back"
  83398. ];
  83399. return HDRCubeTexture;
  83400. }(BABYLON.BaseTexture));
  83401. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83402. })(BABYLON || (BABYLON = {}));
  83403. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83404. var BABYLON;
  83405. (function (BABYLON) {
  83406. var IndexedVector2 = /** @class */ (function (_super) {
  83407. __extends(IndexedVector2, _super);
  83408. function IndexedVector2(original, index) {
  83409. var _this = _super.call(this, original.x, original.y) || this;
  83410. _this.index = index;
  83411. return _this;
  83412. }
  83413. return IndexedVector2;
  83414. }(BABYLON.Vector2));
  83415. var PolygonPoints = /** @class */ (function () {
  83416. function PolygonPoints() {
  83417. this.elements = new Array();
  83418. }
  83419. PolygonPoints.prototype.add = function (originalPoints) {
  83420. var _this = this;
  83421. var result = new Array();
  83422. originalPoints.forEach(function (point) {
  83423. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83424. var newPoint = new IndexedVector2(point, _this.elements.length);
  83425. result.push(newPoint);
  83426. _this.elements.push(newPoint);
  83427. }
  83428. });
  83429. return result;
  83430. };
  83431. PolygonPoints.prototype.computeBounds = function () {
  83432. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83433. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83434. this.elements.forEach(function (point) {
  83435. // x
  83436. if (point.x < lmin.x) {
  83437. lmin.x = point.x;
  83438. }
  83439. else if (point.x > lmax.x) {
  83440. lmax.x = point.x;
  83441. }
  83442. // y
  83443. if (point.y < lmin.y) {
  83444. lmin.y = point.y;
  83445. }
  83446. else if (point.y > lmax.y) {
  83447. lmax.y = point.y;
  83448. }
  83449. });
  83450. return {
  83451. min: lmin,
  83452. max: lmax,
  83453. width: lmax.x - lmin.x,
  83454. height: lmax.y - lmin.y
  83455. };
  83456. };
  83457. return PolygonPoints;
  83458. }());
  83459. var Polygon = /** @class */ (function () {
  83460. function Polygon() {
  83461. }
  83462. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83463. return [
  83464. new BABYLON.Vector2(xmin, ymin),
  83465. new BABYLON.Vector2(xmax, ymin),
  83466. new BABYLON.Vector2(xmax, ymax),
  83467. new BABYLON.Vector2(xmin, ymax)
  83468. ];
  83469. };
  83470. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83471. if (cx === void 0) { cx = 0; }
  83472. if (cy === void 0) { cy = 0; }
  83473. if (numberOfSides === void 0) { numberOfSides = 32; }
  83474. var result = new Array();
  83475. var angle = 0;
  83476. var increment = (Math.PI * 2) / numberOfSides;
  83477. for (var i = 0; i < numberOfSides; i++) {
  83478. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83479. angle -= increment;
  83480. }
  83481. return result;
  83482. };
  83483. Polygon.Parse = function (input) {
  83484. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83485. var i, result = [];
  83486. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83487. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83488. }
  83489. return result;
  83490. };
  83491. Polygon.StartingAt = function (x, y) {
  83492. return BABYLON.Path2.StartingAt(x, y);
  83493. };
  83494. return Polygon;
  83495. }());
  83496. BABYLON.Polygon = Polygon;
  83497. var PolygonMeshBuilder = /** @class */ (function () {
  83498. function PolygonMeshBuilder(name, contours, scene) {
  83499. this._points = new PolygonPoints();
  83500. this._outlinepoints = new PolygonPoints();
  83501. this._holes = new Array();
  83502. this._epoints = new Array();
  83503. this._eholes = new Array();
  83504. this._name = name;
  83505. this._scene = scene;
  83506. var points;
  83507. if (contours instanceof BABYLON.Path2) {
  83508. points = contours.getPoints();
  83509. }
  83510. else {
  83511. points = contours;
  83512. }
  83513. this._addToepoint(points);
  83514. this._points.add(points);
  83515. this._outlinepoints.add(points);
  83516. if (typeof earcut === 'undefined') {
  83517. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83518. }
  83519. }
  83520. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83521. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83522. var p = points_1[_i];
  83523. this._epoints.push(p.x, p.y);
  83524. }
  83525. };
  83526. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83527. this._points.add(hole);
  83528. var holepoints = new PolygonPoints();
  83529. holepoints.add(hole);
  83530. this._holes.push(holepoints);
  83531. this._eholes.push(this._epoints.length / 2);
  83532. this._addToepoint(hole);
  83533. return this;
  83534. };
  83535. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83536. var _this = this;
  83537. if (updatable === void 0) { updatable = false; }
  83538. if (depth === void 0) { depth = 0; }
  83539. var result = new BABYLON.Mesh(this._name, this._scene);
  83540. var normals = new Array();
  83541. var positions = new Array();
  83542. var uvs = new Array();
  83543. var bounds = this._points.computeBounds();
  83544. this._points.elements.forEach(function (p) {
  83545. normals.push(0, 1.0, 0);
  83546. positions.push(p.x, 0, p.y);
  83547. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83548. });
  83549. var indices = new Array();
  83550. var res = earcut(this._epoints, this._eholes, 2);
  83551. for (var i = 0; i < res.length; i++) {
  83552. indices.push(res[i]);
  83553. }
  83554. if (depth > 0) {
  83555. var positionscount = (positions.length / 3); //get the current pointcount
  83556. this._points.elements.forEach(function (p) {
  83557. normals.push(0, -1.0, 0);
  83558. positions.push(p.x, -depth, p.y);
  83559. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83560. });
  83561. var totalCount = indices.length;
  83562. for (var i = 0; i < totalCount; i += 3) {
  83563. var i0 = indices[i + 0];
  83564. var i1 = indices[i + 1];
  83565. var i2 = indices[i + 2];
  83566. indices.push(i2 + positionscount);
  83567. indices.push(i1 + positionscount);
  83568. indices.push(i0 + positionscount);
  83569. }
  83570. //Add the sides
  83571. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83572. this._holes.forEach(function (hole) {
  83573. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83574. });
  83575. }
  83576. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83577. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83578. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83579. result.setIndices(indices);
  83580. return result;
  83581. };
  83582. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83583. var StartIndex = positions.length / 3;
  83584. var ulength = 0;
  83585. for (var i = 0; i < points.elements.length; i++) {
  83586. var p = points.elements[i];
  83587. var p1;
  83588. if ((i + 1) > points.elements.length - 1) {
  83589. p1 = points.elements[0];
  83590. }
  83591. else {
  83592. p1 = points.elements[i + 1];
  83593. }
  83594. positions.push(p.x, 0, p.y);
  83595. positions.push(p.x, -depth, p.y);
  83596. positions.push(p1.x, 0, p1.y);
  83597. positions.push(p1.x, -depth, p1.y);
  83598. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83599. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83600. var v3 = v2.subtract(v1);
  83601. var v4 = new BABYLON.Vector3(0, 1, 0);
  83602. var vn = BABYLON.Vector3.Cross(v3, v4);
  83603. vn = vn.normalize();
  83604. uvs.push(ulength / bounds.width, 0);
  83605. uvs.push(ulength / bounds.width, 1);
  83606. ulength += v3.length();
  83607. uvs.push((ulength / bounds.width), 0);
  83608. uvs.push((ulength / bounds.width), 1);
  83609. if (!flip) {
  83610. normals.push(-vn.x, -vn.y, -vn.z);
  83611. normals.push(-vn.x, -vn.y, -vn.z);
  83612. normals.push(-vn.x, -vn.y, -vn.z);
  83613. normals.push(-vn.x, -vn.y, -vn.z);
  83614. indices.push(StartIndex);
  83615. indices.push(StartIndex + 1);
  83616. indices.push(StartIndex + 2);
  83617. indices.push(StartIndex + 1);
  83618. indices.push(StartIndex + 3);
  83619. indices.push(StartIndex + 2);
  83620. }
  83621. else {
  83622. normals.push(vn.x, vn.y, vn.z);
  83623. normals.push(vn.x, vn.y, vn.z);
  83624. normals.push(vn.x, vn.y, vn.z);
  83625. normals.push(vn.x, vn.y, vn.z);
  83626. indices.push(StartIndex);
  83627. indices.push(StartIndex + 2);
  83628. indices.push(StartIndex + 1);
  83629. indices.push(StartIndex + 1);
  83630. indices.push(StartIndex + 2);
  83631. indices.push(StartIndex + 3);
  83632. }
  83633. StartIndex += 4;
  83634. }
  83635. ;
  83636. };
  83637. return PolygonMeshBuilder;
  83638. }());
  83639. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83640. })(BABYLON || (BABYLON = {}));
  83641. //# sourceMappingURL=babylon.polygonMesh.js.map
  83642. var BABYLON;
  83643. (function (BABYLON) {
  83644. // Unique ID when we import meshes from Babylon to CSG
  83645. var currentCSGMeshId = 0;
  83646. // # class Vertex
  83647. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83648. // one to provide additional features like texture coordinates and vertex
  83649. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83650. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83651. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83652. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83653. // is not used anywhere else.
  83654. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83655. var Vertex = /** @class */ (function () {
  83656. function Vertex(pos, normal, uv) {
  83657. this.pos = pos;
  83658. this.normal = normal;
  83659. this.uv = uv;
  83660. }
  83661. Vertex.prototype.clone = function () {
  83662. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83663. };
  83664. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83665. // orientation of a polygon is flipped.
  83666. Vertex.prototype.flip = function () {
  83667. this.normal = this.normal.scale(-1);
  83668. };
  83669. // Create a new vertex between this vertex and `other` by linearly
  83670. // interpolating all properties using a parameter of `t`. Subclasses should
  83671. // override this to interpolate additional properties.
  83672. Vertex.prototype.interpolate = function (other, t) {
  83673. 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));
  83674. };
  83675. return Vertex;
  83676. }());
  83677. // # class Plane
  83678. // Represents a plane in 3D space.
  83679. var Plane = /** @class */ (function () {
  83680. function Plane(normal, w) {
  83681. this.normal = normal;
  83682. this.w = w;
  83683. }
  83684. Plane.FromPoints = function (a, b, c) {
  83685. var v0 = c.subtract(a);
  83686. var v1 = b.subtract(a);
  83687. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83688. return null;
  83689. }
  83690. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83691. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83692. };
  83693. Plane.prototype.clone = function () {
  83694. return new Plane(this.normal.clone(), this.w);
  83695. };
  83696. Plane.prototype.flip = function () {
  83697. this.normal.scaleInPlace(-1);
  83698. this.w = -this.w;
  83699. };
  83700. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83701. // fragments in the appropriate lists. Coplanar polygons go into either
  83702. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83703. // respect to this plane. Polygons in front or in back of this plane go into
  83704. // either `front` or `back`.
  83705. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83706. var COPLANAR = 0;
  83707. var FRONT = 1;
  83708. var BACK = 2;
  83709. var SPANNING = 3;
  83710. // Classify each point as well as the entire polygon into one of the above
  83711. // four classes.
  83712. var polygonType = 0;
  83713. var types = [];
  83714. var i;
  83715. var t;
  83716. for (i = 0; i < polygon.vertices.length; i++) {
  83717. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83718. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83719. polygonType |= type;
  83720. types.push(type);
  83721. }
  83722. // Put the polygon in the correct list, splitting it when necessary.
  83723. switch (polygonType) {
  83724. case COPLANAR:
  83725. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83726. break;
  83727. case FRONT:
  83728. front.push(polygon);
  83729. break;
  83730. case BACK:
  83731. back.push(polygon);
  83732. break;
  83733. case SPANNING:
  83734. var f = [], b = [];
  83735. for (i = 0; i < polygon.vertices.length; i++) {
  83736. var j = (i + 1) % polygon.vertices.length;
  83737. var ti = types[i], tj = types[j];
  83738. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83739. if (ti !== BACK)
  83740. f.push(vi);
  83741. if (ti !== FRONT)
  83742. b.push(ti !== BACK ? vi.clone() : vi);
  83743. if ((ti | tj) === SPANNING) {
  83744. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83745. var v = vi.interpolate(vj, t);
  83746. f.push(v);
  83747. b.push(v.clone());
  83748. }
  83749. }
  83750. var poly;
  83751. if (f.length >= 3) {
  83752. poly = new Polygon(f, polygon.shared);
  83753. if (poly.plane)
  83754. front.push(poly);
  83755. }
  83756. if (b.length >= 3) {
  83757. poly = new Polygon(b, polygon.shared);
  83758. if (poly.plane)
  83759. back.push(poly);
  83760. }
  83761. break;
  83762. }
  83763. };
  83764. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83765. // point is on the plane.
  83766. Plane.EPSILON = 1e-5;
  83767. return Plane;
  83768. }());
  83769. // # class Polygon
  83770. // Represents a convex polygon. The vertices used to initialize a polygon must
  83771. // be coplanar and form a convex loop.
  83772. //
  83773. // Each convex polygon has a `shared` property, which is shared between all
  83774. // polygons that are clones of each other or were split from the same polygon.
  83775. // This can be used to define per-polygon properties (such as surface color).
  83776. var Polygon = /** @class */ (function () {
  83777. function Polygon(vertices, shared) {
  83778. this.vertices = vertices;
  83779. this.shared = shared;
  83780. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83781. }
  83782. Polygon.prototype.clone = function () {
  83783. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83784. return new Polygon(vertices, this.shared);
  83785. };
  83786. Polygon.prototype.flip = function () {
  83787. this.vertices.reverse().map(function (v) { v.flip(); });
  83788. this.plane.flip();
  83789. };
  83790. return Polygon;
  83791. }());
  83792. // # class Node
  83793. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83794. // by picking a polygon to split along. That polygon (and all other coplanar
  83795. // polygons) are added directly to that node and the other polygons are added to
  83796. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83797. // no distinction between internal and leaf nodes.
  83798. var Node = /** @class */ (function () {
  83799. function Node(polygons) {
  83800. this.plane = null;
  83801. this.front = null;
  83802. this.back = null;
  83803. this.polygons = new Array();
  83804. if (polygons) {
  83805. this.build(polygons);
  83806. }
  83807. }
  83808. Node.prototype.clone = function () {
  83809. var node = new Node();
  83810. node.plane = this.plane && this.plane.clone();
  83811. node.front = this.front && this.front.clone();
  83812. node.back = this.back && this.back.clone();
  83813. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83814. return node;
  83815. };
  83816. // Convert solid space to empty space and empty space to solid space.
  83817. Node.prototype.invert = function () {
  83818. for (var i = 0; i < this.polygons.length; i++) {
  83819. this.polygons[i].flip();
  83820. }
  83821. if (this.plane) {
  83822. this.plane.flip();
  83823. }
  83824. if (this.front) {
  83825. this.front.invert();
  83826. }
  83827. if (this.back) {
  83828. this.back.invert();
  83829. }
  83830. var temp = this.front;
  83831. this.front = this.back;
  83832. this.back = temp;
  83833. };
  83834. // Recursively remove all polygons in `polygons` that are inside this BSP
  83835. // tree.
  83836. Node.prototype.clipPolygons = function (polygons) {
  83837. if (!this.plane)
  83838. return polygons.slice();
  83839. var front = new Array(), back = new Array();
  83840. for (var i = 0; i < polygons.length; i++) {
  83841. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83842. }
  83843. if (this.front) {
  83844. front = this.front.clipPolygons(front);
  83845. }
  83846. if (this.back) {
  83847. back = this.back.clipPolygons(back);
  83848. }
  83849. else {
  83850. back = [];
  83851. }
  83852. return front.concat(back);
  83853. };
  83854. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83855. // `bsp`.
  83856. Node.prototype.clipTo = function (bsp) {
  83857. this.polygons = bsp.clipPolygons(this.polygons);
  83858. if (this.front)
  83859. this.front.clipTo(bsp);
  83860. if (this.back)
  83861. this.back.clipTo(bsp);
  83862. };
  83863. // Return a list of all polygons in this BSP tree.
  83864. Node.prototype.allPolygons = function () {
  83865. var polygons = this.polygons.slice();
  83866. if (this.front)
  83867. polygons = polygons.concat(this.front.allPolygons());
  83868. if (this.back)
  83869. polygons = polygons.concat(this.back.allPolygons());
  83870. return polygons;
  83871. };
  83872. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83873. // new polygons are filtered down to the bottom of the tree and become new
  83874. // nodes there. Each set of polygons is partitioned using the first polygon
  83875. // (no heuristic is used to pick a good split).
  83876. Node.prototype.build = function (polygons) {
  83877. if (!polygons.length)
  83878. return;
  83879. if (!this.plane)
  83880. this.plane = polygons[0].plane.clone();
  83881. var front = new Array(), back = new Array();
  83882. for (var i = 0; i < polygons.length; i++) {
  83883. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83884. }
  83885. if (front.length) {
  83886. if (!this.front)
  83887. this.front = new Node();
  83888. this.front.build(front);
  83889. }
  83890. if (back.length) {
  83891. if (!this.back)
  83892. this.back = new Node();
  83893. this.back.build(back);
  83894. }
  83895. };
  83896. return Node;
  83897. }());
  83898. var CSG = /** @class */ (function () {
  83899. function CSG() {
  83900. this.polygons = new Array();
  83901. }
  83902. // Convert BABYLON.Mesh to BABYLON.CSG
  83903. CSG.FromMesh = function (mesh) {
  83904. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83905. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83906. if (mesh instanceof BABYLON.Mesh) {
  83907. mesh.computeWorldMatrix(true);
  83908. matrix = mesh.getWorldMatrix();
  83909. meshPosition = mesh.position.clone();
  83910. meshRotation = mesh.rotation.clone();
  83911. if (mesh.rotationQuaternion) {
  83912. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83913. }
  83914. meshScaling = mesh.scaling.clone();
  83915. }
  83916. else {
  83917. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83918. }
  83919. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83920. var subMeshes = mesh.subMeshes;
  83921. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83922. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83923. vertices = [];
  83924. for (var j = 0; j < 3; j++) {
  83925. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83926. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83927. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83928. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83929. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83930. vertex = new Vertex(position, normal, uv);
  83931. vertices.push(vertex);
  83932. }
  83933. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83934. // To handle the case of degenerated triangle
  83935. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83936. if (polygon.plane)
  83937. polygons.push(polygon);
  83938. }
  83939. }
  83940. var csg = CSG.FromPolygons(polygons);
  83941. csg.matrix = matrix;
  83942. csg.position = meshPosition;
  83943. csg.rotation = meshRotation;
  83944. csg.scaling = meshScaling;
  83945. csg.rotationQuaternion = meshRotationQuaternion;
  83946. currentCSGMeshId++;
  83947. return csg;
  83948. };
  83949. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83950. CSG.FromPolygons = function (polygons) {
  83951. var csg = new CSG();
  83952. csg.polygons = polygons;
  83953. return csg;
  83954. };
  83955. CSG.prototype.clone = function () {
  83956. var csg = new CSG();
  83957. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83958. csg.copyTransformAttributes(this);
  83959. return csg;
  83960. };
  83961. CSG.prototype.union = function (csg) {
  83962. var a = new Node(this.clone().polygons);
  83963. var b = new Node(csg.clone().polygons);
  83964. a.clipTo(b);
  83965. b.clipTo(a);
  83966. b.invert();
  83967. b.clipTo(a);
  83968. b.invert();
  83969. a.build(b.allPolygons());
  83970. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83971. };
  83972. CSG.prototype.unionInPlace = function (csg) {
  83973. var a = new Node(this.polygons);
  83974. var b = new Node(csg.polygons);
  83975. a.clipTo(b);
  83976. b.clipTo(a);
  83977. b.invert();
  83978. b.clipTo(a);
  83979. b.invert();
  83980. a.build(b.allPolygons());
  83981. this.polygons = a.allPolygons();
  83982. };
  83983. CSG.prototype.subtract = function (csg) {
  83984. var a = new Node(this.clone().polygons);
  83985. var b = new Node(csg.clone().polygons);
  83986. a.invert();
  83987. a.clipTo(b);
  83988. b.clipTo(a);
  83989. b.invert();
  83990. b.clipTo(a);
  83991. b.invert();
  83992. a.build(b.allPolygons());
  83993. a.invert();
  83994. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83995. };
  83996. CSG.prototype.subtractInPlace = function (csg) {
  83997. var a = new Node(this.polygons);
  83998. var b = new Node(csg.polygons);
  83999. a.invert();
  84000. a.clipTo(b);
  84001. b.clipTo(a);
  84002. b.invert();
  84003. b.clipTo(a);
  84004. b.invert();
  84005. a.build(b.allPolygons());
  84006. a.invert();
  84007. this.polygons = a.allPolygons();
  84008. };
  84009. CSG.prototype.intersect = function (csg) {
  84010. var a = new Node(this.clone().polygons);
  84011. var b = new Node(csg.clone().polygons);
  84012. a.invert();
  84013. b.clipTo(a);
  84014. b.invert();
  84015. a.clipTo(b);
  84016. b.clipTo(a);
  84017. a.build(b.allPolygons());
  84018. a.invert();
  84019. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  84020. };
  84021. CSG.prototype.intersectInPlace = function (csg) {
  84022. var a = new Node(this.polygons);
  84023. var b = new Node(csg.polygons);
  84024. a.invert();
  84025. b.clipTo(a);
  84026. b.invert();
  84027. a.clipTo(b);
  84028. b.clipTo(a);
  84029. a.build(b.allPolygons());
  84030. a.invert();
  84031. this.polygons = a.allPolygons();
  84032. };
  84033. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  84034. // not modified.
  84035. CSG.prototype.inverse = function () {
  84036. var csg = this.clone();
  84037. csg.inverseInPlace();
  84038. return csg;
  84039. };
  84040. CSG.prototype.inverseInPlace = function () {
  84041. this.polygons.map(function (p) { p.flip(); });
  84042. };
  84043. // This is used to keep meshes transformations so they can be restored
  84044. // when we build back a Babylon Mesh
  84045. // NB : All CSG operations are performed in world coordinates
  84046. CSG.prototype.copyTransformAttributes = function (csg) {
  84047. this.matrix = csg.matrix;
  84048. this.position = csg.position;
  84049. this.rotation = csg.rotation;
  84050. this.scaling = csg.scaling;
  84051. this.rotationQuaternion = csg.rotationQuaternion;
  84052. return this;
  84053. };
  84054. // Build Raw mesh from CSG
  84055. // Coordinates here are in world space
  84056. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  84057. var matrix = this.matrix.clone();
  84058. matrix.invert();
  84059. 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;
  84060. if (keepSubMeshes) {
  84061. // Sort Polygons, since subMeshes are indices range
  84062. polygons.sort(function (a, b) {
  84063. if (a.shared.meshId === b.shared.meshId) {
  84064. return a.shared.subMeshId - b.shared.subMeshId;
  84065. }
  84066. else {
  84067. return a.shared.meshId - b.shared.meshId;
  84068. }
  84069. });
  84070. }
  84071. for (var i = 0, il = polygons.length; i < il; i++) {
  84072. polygon = polygons[i];
  84073. // Building SubMeshes
  84074. if (!subMesh_dict[polygon.shared.meshId]) {
  84075. subMesh_dict[polygon.shared.meshId] = {};
  84076. }
  84077. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  84078. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  84079. indexStart: +Infinity,
  84080. indexEnd: -Infinity,
  84081. materialIndex: polygon.shared.materialIndex
  84082. };
  84083. }
  84084. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  84085. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  84086. polygonIndices[0] = 0;
  84087. polygonIndices[1] = j - 1;
  84088. polygonIndices[2] = j;
  84089. for (var k = 0; k < 3; k++) {
  84090. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  84091. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  84092. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  84093. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  84094. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  84095. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  84096. // Check if 2 points can be merged
  84097. if (!(typeof vertex_idx !== 'undefined' &&
  84098. normals[vertex_idx * 3] === localNormal.x &&
  84099. normals[vertex_idx * 3 + 1] === localNormal.y &&
  84100. normals[vertex_idx * 3 + 2] === localNormal.z &&
  84101. uvs[vertex_idx * 2] === uv.x &&
  84102. uvs[vertex_idx * 2 + 1] === uv.y)) {
  84103. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  84104. uvs.push(uv.x, uv.y);
  84105. normals.push(normal.x, normal.y, normal.z);
  84106. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  84107. }
  84108. indices.push(vertex_idx);
  84109. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  84110. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  84111. currentIndex++;
  84112. }
  84113. }
  84114. }
  84115. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  84116. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  84117. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  84118. mesh.setIndices(indices, null);
  84119. if (keepSubMeshes) {
  84120. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  84121. var materialIndexOffset = 0, materialMaxIndex;
  84122. mesh.subMeshes = new Array();
  84123. for (var m in subMesh_dict) {
  84124. materialMaxIndex = -1;
  84125. for (var sm in subMesh_dict[m]) {
  84126. subMesh_obj = subMesh_dict[m][sm];
  84127. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  84128. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  84129. }
  84130. materialIndexOffset += ++materialMaxIndex;
  84131. }
  84132. }
  84133. return mesh;
  84134. };
  84135. // Build Mesh from CSG taking material and transforms into account
  84136. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  84137. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  84138. mesh.material = material;
  84139. mesh.position.copyFrom(this.position);
  84140. mesh.rotation.copyFrom(this.rotation);
  84141. if (this.rotationQuaternion) {
  84142. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  84143. }
  84144. mesh.scaling.copyFrom(this.scaling);
  84145. mesh.computeWorldMatrix(true);
  84146. return mesh;
  84147. };
  84148. return CSG;
  84149. }());
  84150. BABYLON.CSG = CSG;
  84151. })(BABYLON || (BABYLON = {}));
  84152. //# sourceMappingURL=babylon.csg.js.map
  84153. var BABYLON;
  84154. (function (BABYLON) {
  84155. var LensFlare = /** @class */ (function () {
  84156. function LensFlare(size, position, color, imgUrl, system) {
  84157. this.size = size;
  84158. this.position = position;
  84159. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  84160. this.color = color || new BABYLON.Color3(1, 1, 1);
  84161. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  84162. this._system = system;
  84163. system.lensFlares.push(this);
  84164. }
  84165. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  84166. return new LensFlare(size, position, color, imgUrl, system);
  84167. };
  84168. LensFlare.prototype.dispose = function () {
  84169. if (this.texture) {
  84170. this.texture.dispose();
  84171. }
  84172. // Remove from scene
  84173. var index = this._system.lensFlares.indexOf(this);
  84174. this._system.lensFlares.splice(index, 1);
  84175. };
  84176. ;
  84177. return LensFlare;
  84178. }());
  84179. BABYLON.LensFlare = LensFlare;
  84180. })(BABYLON || (BABYLON = {}));
  84181. //# sourceMappingURL=babylon.lensFlare.js.map
  84182. var BABYLON;
  84183. (function (BABYLON) {
  84184. // Adds the parser to the scene parsers.
  84185. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  84186. // Lens flares
  84187. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  84188. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  84189. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  84190. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  84191. container.lensFlareSystems.push(lf);
  84192. }
  84193. }
  84194. });
  84195. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  84196. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84197. if (this.lensFlareSystems[index].name === name) {
  84198. return this.lensFlareSystems[index];
  84199. }
  84200. }
  84201. return null;
  84202. };
  84203. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  84204. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  84205. if (this.lensFlareSystems[index].id === id) {
  84206. return this.lensFlareSystems[index];
  84207. }
  84208. }
  84209. return null;
  84210. };
  84211. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  84212. var index = this.lensFlareSystems.indexOf(toRemove);
  84213. if (index !== -1) {
  84214. this.lensFlareSystems.splice(index, 1);
  84215. }
  84216. return index;
  84217. };
  84218. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  84219. this.lensFlareSystems.push(newLensFlareSystem);
  84220. };
  84221. /**
  84222. * Defines the lens flare scene component responsible to manage any lens flares
  84223. * in a given scene.
  84224. */
  84225. var LensFlareSystemSceneComponent = /** @class */ (function () {
  84226. /**
  84227. * Creates a new instance of the component for the given scene
  84228. * @param scene Defines the scene to register the component in
  84229. */
  84230. function LensFlareSystemSceneComponent(scene) {
  84231. /**
  84232. * The component name helpfull to identify the component in the list of scene components.
  84233. */
  84234. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  84235. this.scene = scene;
  84236. scene.lensFlareSystems = new Array();
  84237. }
  84238. /**
  84239. * Registers the component in a given scene
  84240. */
  84241. LensFlareSystemSceneComponent.prototype.register = function () {
  84242. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  84243. };
  84244. /**
  84245. * Rebuilds the elements related to this component in case of
  84246. * context lost for instance.
  84247. */
  84248. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  84249. // Nothing to do for lens flare
  84250. };
  84251. /**
  84252. * Adds all the element from the container to the scene
  84253. * @param container the container holding the elements
  84254. */
  84255. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  84256. var _this = this;
  84257. if (!container.lensFlareSystems) {
  84258. return;
  84259. }
  84260. container.lensFlareSystems.forEach(function (o) {
  84261. _this.scene.addLensFlareSystem(o);
  84262. });
  84263. };
  84264. /**
  84265. * Removes all the elements in the container from the scene
  84266. * @param container contains the elements to remove
  84267. */
  84268. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  84269. var _this = this;
  84270. if (!container.lensFlareSystems) {
  84271. return;
  84272. }
  84273. container.lensFlareSystems.forEach(function (o) {
  84274. _this.scene.removeLensFlareSystem(o);
  84275. });
  84276. };
  84277. /**
  84278. * Serializes the component data to the specified json object
  84279. * @param serializationObject The object to serialize to
  84280. */
  84281. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  84282. // Lens flares
  84283. serializationObject.lensFlareSystems = [];
  84284. var lensFlareSystems = this.scene.lensFlareSystems;
  84285. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  84286. var lensFlareSystem = lensFlareSystems_1[_i];
  84287. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  84288. }
  84289. };
  84290. /**
  84291. * Disposes the component and the associated ressources.
  84292. */
  84293. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84294. var lensFlareSystems = this.scene.lensFlareSystems;
  84295. while (lensFlareSystems.length) {
  84296. lensFlareSystems[0].dispose();
  84297. }
  84298. };
  84299. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84300. // Lens flares
  84301. if (this.scene.lensFlaresEnabled) {
  84302. var lensFlareSystems = this.scene.lensFlareSystems;
  84303. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84304. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  84305. var lensFlareSystem = lensFlareSystems_2[_i];
  84306. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84307. lensFlareSystem.render();
  84308. }
  84309. }
  84310. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  84311. }
  84312. };
  84313. return LensFlareSystemSceneComponent;
  84314. }());
  84315. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84316. })(BABYLON || (BABYLON = {}));
  84317. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84318. var BABYLON;
  84319. (function (BABYLON) {
  84320. var LensFlareSystem = /** @class */ (function () {
  84321. function LensFlareSystem(name, emitter, scene) {
  84322. this.name = name;
  84323. this.lensFlares = new Array();
  84324. this.borderLimit = 300;
  84325. this.viewportBorder = 0;
  84326. this.layerMask = 0x0FFFFFFF;
  84327. this._vertexBuffers = {};
  84328. this._isEnabled = true;
  84329. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84330. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84331. if (!component) {
  84332. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84333. scene._addComponent(component);
  84334. }
  84335. this._emitter = emitter;
  84336. this.id = name;
  84337. scene.lensFlareSystems.push(this);
  84338. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84339. var engine = scene.getEngine();
  84340. // VBO
  84341. var vertices = [];
  84342. vertices.push(1, 1);
  84343. vertices.push(-1, 1);
  84344. vertices.push(-1, -1);
  84345. vertices.push(1, -1);
  84346. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84347. // Indices
  84348. var indices = [];
  84349. indices.push(0);
  84350. indices.push(1);
  84351. indices.push(2);
  84352. indices.push(0);
  84353. indices.push(2);
  84354. indices.push(3);
  84355. this._indexBuffer = engine.createIndexBuffer(indices);
  84356. // Effects
  84357. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84358. }
  84359. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84360. get: function () {
  84361. return this._isEnabled;
  84362. },
  84363. set: function (value) {
  84364. this._isEnabled = value;
  84365. },
  84366. enumerable: true,
  84367. configurable: true
  84368. });
  84369. LensFlareSystem.prototype.getScene = function () {
  84370. return this._scene;
  84371. };
  84372. LensFlareSystem.prototype.getEmitter = function () {
  84373. return this._emitter;
  84374. };
  84375. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84376. this._emitter = newEmitter;
  84377. };
  84378. LensFlareSystem.prototype.getEmitterPosition = function () {
  84379. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84380. };
  84381. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84382. var position = this.getEmitterPosition();
  84383. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84384. this._positionX = position.x;
  84385. this._positionY = position.y;
  84386. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84387. if (this.viewportBorder > 0) {
  84388. globalViewport.x -= this.viewportBorder;
  84389. globalViewport.y -= this.viewportBorder;
  84390. globalViewport.width += this.viewportBorder * 2;
  84391. globalViewport.height += this.viewportBorder * 2;
  84392. position.x += this.viewportBorder;
  84393. position.y += this.viewportBorder;
  84394. this._positionX += this.viewportBorder;
  84395. this._positionY += this.viewportBorder;
  84396. }
  84397. if (position.z > 0) {
  84398. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84399. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84400. return true;
  84401. }
  84402. return true;
  84403. }
  84404. return false;
  84405. };
  84406. LensFlareSystem.prototype._isVisible = function () {
  84407. if (!this._isEnabled || !this._scene.activeCamera) {
  84408. return false;
  84409. }
  84410. var emitterPosition = this.getEmitterPosition();
  84411. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84412. var distance = direction.length();
  84413. direction.normalize();
  84414. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84415. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84416. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84417. };
  84418. LensFlareSystem.prototype.render = function () {
  84419. if (!this._effect.isReady() || !this._scene.activeCamera)
  84420. return false;
  84421. var engine = this._scene.getEngine();
  84422. var viewport = this._scene.activeCamera.viewport;
  84423. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84424. // Position
  84425. if (!this.computeEffectivePosition(globalViewport)) {
  84426. return false;
  84427. }
  84428. // Visibility
  84429. if (!this._isVisible()) {
  84430. return false;
  84431. }
  84432. // Intensity
  84433. var awayX;
  84434. var awayY;
  84435. if (this._positionX < this.borderLimit + globalViewport.x) {
  84436. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84437. }
  84438. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84439. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84440. }
  84441. else {
  84442. awayX = 0;
  84443. }
  84444. if (this._positionY < this.borderLimit + globalViewport.y) {
  84445. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84446. }
  84447. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84448. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84449. }
  84450. else {
  84451. awayY = 0;
  84452. }
  84453. var away = (awayX > awayY) ? awayX : awayY;
  84454. away -= this.viewportBorder;
  84455. if (away > this.borderLimit) {
  84456. away = this.borderLimit;
  84457. }
  84458. var intensity = 1.0 - (away / this.borderLimit);
  84459. if (intensity < 0) {
  84460. return false;
  84461. }
  84462. if (intensity > 1.0) {
  84463. intensity = 1.0;
  84464. }
  84465. if (this.viewportBorder > 0) {
  84466. globalViewport.x += this.viewportBorder;
  84467. globalViewport.y += this.viewportBorder;
  84468. globalViewport.width -= this.viewportBorder * 2;
  84469. globalViewport.height -= this.viewportBorder * 2;
  84470. this._positionX -= this.viewportBorder;
  84471. this._positionY -= this.viewportBorder;
  84472. }
  84473. // Position
  84474. var centerX = globalViewport.x + globalViewport.width / 2;
  84475. var centerY = globalViewport.y + globalViewport.height / 2;
  84476. var distX = centerX - this._positionX;
  84477. var distY = centerY - this._positionY;
  84478. // Effects
  84479. engine.enableEffect(this._effect);
  84480. engine.setState(false);
  84481. engine.setDepthBuffer(false);
  84482. // VBOs
  84483. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84484. // Flares
  84485. for (var index = 0; index < this.lensFlares.length; index++) {
  84486. var flare = this.lensFlares[index];
  84487. engine.setAlphaMode(flare.alphaMode);
  84488. var x = centerX - (distX * flare.position);
  84489. var y = centerY - (distY * flare.position);
  84490. var cw = flare.size;
  84491. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84492. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84493. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84494. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84495. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84496. // Texture
  84497. this._effect.setTexture("textureSampler", flare.texture);
  84498. // Color
  84499. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84500. // Draw order
  84501. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84502. }
  84503. engine.setDepthBuffer(true);
  84504. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84505. return true;
  84506. };
  84507. LensFlareSystem.prototype.dispose = function () {
  84508. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84509. if (vertexBuffer) {
  84510. vertexBuffer.dispose();
  84511. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84512. }
  84513. if (this._indexBuffer) {
  84514. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84515. this._indexBuffer = null;
  84516. }
  84517. while (this.lensFlares.length) {
  84518. this.lensFlares[0].dispose();
  84519. }
  84520. // Remove from scene
  84521. var index = this._scene.lensFlareSystems.indexOf(this);
  84522. this._scene.lensFlareSystems.splice(index, 1);
  84523. };
  84524. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84525. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84526. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84527. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84528. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84529. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84530. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84531. var parsedFlare = parsedLensFlareSystem.flares[index];
  84532. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84533. }
  84534. return lensFlareSystem;
  84535. };
  84536. LensFlareSystem.prototype.serialize = function () {
  84537. var serializationObject = {};
  84538. serializationObject.id = this.id;
  84539. serializationObject.name = this.name;
  84540. serializationObject.emitterId = this.getEmitter().id;
  84541. serializationObject.borderLimit = this.borderLimit;
  84542. serializationObject.flares = [];
  84543. for (var index = 0; index < this.lensFlares.length; index++) {
  84544. var flare = this.lensFlares[index];
  84545. serializationObject.flares.push({
  84546. size: flare.size,
  84547. position: flare.position,
  84548. color: flare.color.asArray(),
  84549. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84550. });
  84551. }
  84552. return serializationObject;
  84553. };
  84554. return LensFlareSystem;
  84555. }());
  84556. BABYLON.LensFlareSystem = LensFlareSystem;
  84557. })(BABYLON || (BABYLON = {}));
  84558. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84559. var BABYLON;
  84560. (function (BABYLON) {
  84561. /**
  84562. * This is a holder class for the physics joint created by the physics plugin.
  84563. * It holds a set of functions to control the underlying joint.
  84564. */
  84565. var PhysicsJoint = /** @class */ (function () {
  84566. function PhysicsJoint(type, jointData) {
  84567. this.type = type;
  84568. this.jointData = jointData;
  84569. jointData.nativeParams = jointData.nativeParams || {};
  84570. }
  84571. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84572. get: function () {
  84573. return this._physicsJoint;
  84574. },
  84575. set: function (newJoint) {
  84576. if (this._physicsJoint) {
  84577. //remove from the wolrd
  84578. }
  84579. this._physicsJoint = newJoint;
  84580. },
  84581. enumerable: true,
  84582. configurable: true
  84583. });
  84584. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84585. set: function (physicsPlugin) {
  84586. this._physicsPlugin = physicsPlugin;
  84587. },
  84588. enumerable: true,
  84589. configurable: true
  84590. });
  84591. /**
  84592. * Execute a function that is physics-plugin specific.
  84593. * @param {Function} func the function that will be executed.
  84594. * It accepts two parameters: the physics world and the physics joint.
  84595. */
  84596. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84597. func(this._physicsPlugin.world, this._physicsJoint);
  84598. };
  84599. //TODO check if the native joints are the same
  84600. //Joint Types
  84601. PhysicsJoint.DistanceJoint = 0;
  84602. PhysicsJoint.HingeJoint = 1;
  84603. PhysicsJoint.BallAndSocketJoint = 2;
  84604. PhysicsJoint.WheelJoint = 3;
  84605. PhysicsJoint.SliderJoint = 4;
  84606. //OIMO
  84607. PhysicsJoint.PrismaticJoint = 5;
  84608. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84609. PhysicsJoint.UniversalJoint = 6;
  84610. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84611. //Cannon
  84612. //Similar to a Ball-Joint. Different in params
  84613. PhysicsJoint.PointToPointJoint = 8;
  84614. //Cannon only at the moment
  84615. PhysicsJoint.SpringJoint = 9;
  84616. PhysicsJoint.LockJoint = 10;
  84617. return PhysicsJoint;
  84618. }());
  84619. BABYLON.PhysicsJoint = PhysicsJoint;
  84620. /**
  84621. * A class representing a physics distance joint.
  84622. */
  84623. var DistanceJoint = /** @class */ (function (_super) {
  84624. __extends(DistanceJoint, _super);
  84625. function DistanceJoint(jointData) {
  84626. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84627. }
  84628. /**
  84629. * Update the predefined distance.
  84630. */
  84631. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84632. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84633. };
  84634. return DistanceJoint;
  84635. }(PhysicsJoint));
  84636. BABYLON.DistanceJoint = DistanceJoint;
  84637. var MotorEnabledJoint = /** @class */ (function (_super) {
  84638. __extends(MotorEnabledJoint, _super);
  84639. function MotorEnabledJoint(type, jointData) {
  84640. return _super.call(this, type, jointData) || this;
  84641. }
  84642. /**
  84643. * Set the motor values.
  84644. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84645. * @param {number} force the force to apply
  84646. * @param {number} maxForce max force for this motor.
  84647. */
  84648. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84649. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84650. };
  84651. /**
  84652. * Set the motor's limits.
  84653. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84654. */
  84655. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84656. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84657. };
  84658. return MotorEnabledJoint;
  84659. }(PhysicsJoint));
  84660. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84661. /**
  84662. * This class represents a single hinge physics joint
  84663. */
  84664. var HingeJoint = /** @class */ (function (_super) {
  84665. __extends(HingeJoint, _super);
  84666. function HingeJoint(jointData) {
  84667. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84668. }
  84669. /**
  84670. * Set the motor values.
  84671. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84672. * @param {number} force the force to apply
  84673. * @param {number} maxForce max force for this motor.
  84674. */
  84675. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84676. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84677. };
  84678. /**
  84679. * Set the motor's limits.
  84680. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84681. */
  84682. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84683. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84684. };
  84685. return HingeJoint;
  84686. }(MotorEnabledJoint));
  84687. BABYLON.HingeJoint = HingeJoint;
  84688. /**
  84689. * This class represents a dual hinge physics joint (same as wheel joint)
  84690. */
  84691. var Hinge2Joint = /** @class */ (function (_super) {
  84692. __extends(Hinge2Joint, _super);
  84693. function Hinge2Joint(jointData) {
  84694. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84695. }
  84696. /**
  84697. * Set the motor values.
  84698. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84699. * @param {number} force the force to apply
  84700. * @param {number} maxForce max force for this motor.
  84701. * @param {motorIndex} the motor's index, 0 or 1.
  84702. */
  84703. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84704. if (motorIndex === void 0) { motorIndex = 0; }
  84705. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84706. };
  84707. /**
  84708. * Set the motor limits.
  84709. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84710. * @param {number} upperLimit the upper limit
  84711. * @param {number} lowerLimit lower limit
  84712. * @param {motorIndex} the motor's index, 0 or 1.
  84713. */
  84714. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84715. if (motorIndex === void 0) { motorIndex = 0; }
  84716. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84717. };
  84718. return Hinge2Joint;
  84719. }(MotorEnabledJoint));
  84720. BABYLON.Hinge2Joint = Hinge2Joint;
  84721. })(BABYLON || (BABYLON = {}));
  84722. //# sourceMappingURL=babylon.physicsJoint.js.map
  84723. var BABYLON;
  84724. (function (BABYLON) {
  84725. var PhysicsImpostor = /** @class */ (function () {
  84726. function PhysicsImpostor(object, type, _options, _scene) {
  84727. if (_options === void 0) { _options = { mass: 0 }; }
  84728. var _this = this;
  84729. this.object = object;
  84730. this.type = type;
  84731. this._options = _options;
  84732. this._scene = _scene;
  84733. this._bodyUpdateRequired = false;
  84734. this._onBeforePhysicsStepCallbacks = new Array();
  84735. this._onAfterPhysicsStepCallbacks = new Array();
  84736. this._onPhysicsCollideCallbacks = [];
  84737. this._deltaPosition = BABYLON.Vector3.Zero();
  84738. this._isDisposed = false;
  84739. //temp variables for parent rotation calculations
  84740. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84741. this._tmpQuat = new BABYLON.Quaternion();
  84742. this._tmpQuat2 = new BABYLON.Quaternion();
  84743. /**
  84744. * this function is executed by the physics engine.
  84745. */
  84746. this.beforeStep = function () {
  84747. if (!_this._physicsEngine) {
  84748. return;
  84749. }
  84750. _this.object.translate(_this._deltaPosition, -1);
  84751. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84752. _this.object.computeWorldMatrix(false);
  84753. if (_this.object.parent && _this.object.rotationQuaternion) {
  84754. _this.getParentsRotation();
  84755. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84756. }
  84757. else {
  84758. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84759. }
  84760. if (!_this._options.disableBidirectionalTransformation) {
  84761. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84762. }
  84763. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84764. func(_this);
  84765. });
  84766. };
  84767. /**
  84768. * this function is executed by the physics engine.
  84769. */
  84770. this.afterStep = function () {
  84771. if (!_this._physicsEngine) {
  84772. return;
  84773. }
  84774. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84775. func(_this);
  84776. });
  84777. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84778. // object has now its world rotation. needs to be converted to local.
  84779. if (_this.object.parent && _this.object.rotationQuaternion) {
  84780. _this.getParentsRotation();
  84781. _this._tmpQuat.conjugateInPlace();
  84782. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84783. }
  84784. // take the position set and make it the absolute position of this object.
  84785. _this.object.setAbsolutePosition(_this.object.position);
  84786. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84787. _this.object.translate(_this._deltaPosition, 1);
  84788. };
  84789. /**
  84790. * Legacy collision detection event support
  84791. */
  84792. this.onCollideEvent = null;
  84793. //event and body object due to cannon's event-based architecture.
  84794. this.onCollide = function (e) {
  84795. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84796. return;
  84797. }
  84798. if (!_this._physicsEngine) {
  84799. return;
  84800. }
  84801. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84802. if (otherImpostor) {
  84803. // Legacy collision detection event support
  84804. if (_this.onCollideEvent) {
  84805. _this.onCollideEvent(_this, otherImpostor);
  84806. }
  84807. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84808. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84809. }).forEach(function (obj) {
  84810. obj.callback(_this, otherImpostor);
  84811. });
  84812. }
  84813. };
  84814. //sanity check!
  84815. if (!this.object) {
  84816. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84817. return;
  84818. }
  84819. //legacy support for old syntax.
  84820. if (!this._scene && object.getScene) {
  84821. this._scene = object.getScene();
  84822. }
  84823. if (!this._scene) {
  84824. return;
  84825. }
  84826. this._physicsEngine = this._scene.getPhysicsEngine();
  84827. if (!this._physicsEngine) {
  84828. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84829. }
  84830. else {
  84831. //set the object's quaternion, if not set
  84832. if (!this.object.rotationQuaternion) {
  84833. if (this.object.rotation) {
  84834. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84835. }
  84836. else {
  84837. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84838. }
  84839. }
  84840. //default options params
  84841. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84842. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84843. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84844. this._joints = [];
  84845. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84846. if (!this.object.parent || this._options.ignoreParent) {
  84847. this._init();
  84848. }
  84849. else if (this.object.parent.physicsImpostor) {
  84850. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84851. }
  84852. }
  84853. }
  84854. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84855. get: function () {
  84856. return this._isDisposed;
  84857. },
  84858. enumerable: true,
  84859. configurable: true
  84860. });
  84861. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84862. get: function () {
  84863. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84864. },
  84865. set: function (value) {
  84866. this.setMass(value);
  84867. },
  84868. enumerable: true,
  84869. configurable: true
  84870. });
  84871. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84872. get: function () {
  84873. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84874. },
  84875. set: function (value) {
  84876. if (!this._physicsEngine) {
  84877. return;
  84878. }
  84879. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84880. },
  84881. enumerable: true,
  84882. configurable: true
  84883. });
  84884. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84885. get: function () {
  84886. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84887. },
  84888. set: function (value) {
  84889. if (!this._physicsEngine) {
  84890. return;
  84891. }
  84892. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84893. },
  84894. enumerable: true,
  84895. configurable: true
  84896. });
  84897. /**
  84898. * This function will completly initialize this impostor.
  84899. * It will create a new body - but only if this mesh has no parent.
  84900. * If it has, this impostor will not be used other than to define the impostor
  84901. * of the child mesh.
  84902. */
  84903. PhysicsImpostor.prototype._init = function () {
  84904. if (!this._physicsEngine) {
  84905. return;
  84906. }
  84907. this._physicsEngine.removeImpostor(this);
  84908. this.physicsBody = null;
  84909. this._parent = this._parent || this._getPhysicsParent();
  84910. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84911. this._physicsEngine.addImpostor(this);
  84912. }
  84913. };
  84914. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84915. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84916. var parentMesh = this.object.parent;
  84917. return parentMesh.physicsImpostor;
  84918. }
  84919. return null;
  84920. };
  84921. /**
  84922. * Should a new body be generated.
  84923. */
  84924. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84925. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84926. };
  84927. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84928. this.forceUpdate();
  84929. };
  84930. /**
  84931. * Force a regeneration of this or the parent's impostor's body.
  84932. * Use under cautious - This will remove all joints already implemented.
  84933. */
  84934. PhysicsImpostor.prototype.forceUpdate = function () {
  84935. this._init();
  84936. if (this.parent && !this._options.ignoreParent) {
  84937. this.parent.forceUpdate();
  84938. }
  84939. };
  84940. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84941. /*public get mesh(): AbstractMesh {
  84942. return this._mesh;
  84943. }*/
  84944. /**
  84945. * Gets the body that holds this impostor. Either its own, or its parent.
  84946. */
  84947. get: function () {
  84948. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84949. },
  84950. /**
  84951. * Set the physics body. Used mainly by the physics engine/plugin
  84952. */
  84953. set: function (physicsBody) {
  84954. if (this._physicsBody && this._physicsEngine) {
  84955. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84956. }
  84957. this._physicsBody = physicsBody;
  84958. this.resetUpdateFlags();
  84959. },
  84960. enumerable: true,
  84961. configurable: true
  84962. });
  84963. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84964. get: function () {
  84965. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84966. },
  84967. set: function (value) {
  84968. this._parent = value;
  84969. },
  84970. enumerable: true,
  84971. configurable: true
  84972. });
  84973. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84974. this._bodyUpdateRequired = false;
  84975. };
  84976. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84977. if (this.object.getBoundingInfo) {
  84978. var q = this.object.rotationQuaternion;
  84979. //reset rotation
  84980. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84981. //calculate the world matrix with no rotation
  84982. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84983. var boundingInfo = this.object.getBoundingInfo();
  84984. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84985. //bring back the rotation
  84986. this.object.rotationQuaternion = q;
  84987. //calculate the world matrix with the new rotation
  84988. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84989. return size;
  84990. }
  84991. else {
  84992. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84993. }
  84994. };
  84995. PhysicsImpostor.prototype.getObjectCenter = function () {
  84996. if (this.object.getBoundingInfo) {
  84997. var boundingInfo = this.object.getBoundingInfo();
  84998. return boundingInfo.boundingBox.centerWorld;
  84999. }
  85000. else {
  85001. return this.object.position;
  85002. }
  85003. };
  85004. /**
  85005. * Get a specific parametes from the options parameter.
  85006. */
  85007. PhysicsImpostor.prototype.getParam = function (paramName) {
  85008. return this._options[paramName];
  85009. };
  85010. /**
  85011. * Sets a specific parameter in the options given to the physics plugin
  85012. */
  85013. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  85014. this._options[paramName] = value;
  85015. this._bodyUpdateRequired = true;
  85016. };
  85017. /**
  85018. * Specifically change the body's mass option. Won't recreate the physics body object
  85019. */
  85020. PhysicsImpostor.prototype.setMass = function (mass) {
  85021. if (this.getParam("mass") !== mass) {
  85022. this.setParam("mass", mass);
  85023. }
  85024. if (this._physicsEngine) {
  85025. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  85026. }
  85027. };
  85028. PhysicsImpostor.prototype.getLinearVelocity = function () {
  85029. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  85030. };
  85031. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  85032. if (this._physicsEngine) {
  85033. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  85034. }
  85035. };
  85036. PhysicsImpostor.prototype.getAngularVelocity = function () {
  85037. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  85038. };
  85039. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  85040. if (this._physicsEngine) {
  85041. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  85042. }
  85043. };
  85044. /**
  85045. * Execute a function with the physics plugin native code.
  85046. * Provide a function the will have two variables - the world object and the physics body object.
  85047. */
  85048. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  85049. if (this._physicsEngine) {
  85050. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  85051. }
  85052. };
  85053. /**
  85054. * Register a function that will be executed before the physics world is stepping forward.
  85055. */
  85056. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  85057. this._onBeforePhysicsStepCallbacks.push(func);
  85058. };
  85059. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  85060. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  85061. if (index > -1) {
  85062. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  85063. }
  85064. else {
  85065. BABYLON.Tools.Warn("Function to remove was not found");
  85066. }
  85067. };
  85068. /**
  85069. * Register a function that will be executed after the physics step
  85070. */
  85071. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  85072. this._onAfterPhysicsStepCallbacks.push(func);
  85073. };
  85074. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  85075. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  85076. if (index > -1) {
  85077. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  85078. }
  85079. else {
  85080. BABYLON.Tools.Warn("Function to remove was not found");
  85081. }
  85082. };
  85083. /**
  85084. * register a function that will be executed when this impostor collides against a different body.
  85085. */
  85086. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  85087. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85088. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  85089. };
  85090. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  85091. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  85092. var index = -1;
  85093. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  85094. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  85095. // chcek the arrays match
  85096. var sameList = cbDef.otherImpostors.every(function (impostor) {
  85097. return collidedAgainstList.indexOf(impostor) > -1;
  85098. });
  85099. if (sameList) {
  85100. index = idx;
  85101. }
  85102. return sameList;
  85103. }
  85104. return false;
  85105. });
  85106. if (found) {
  85107. this._onPhysicsCollideCallbacks.splice(index, 1);
  85108. }
  85109. else {
  85110. BABYLON.Tools.Warn("Function to remove was not found");
  85111. }
  85112. };
  85113. PhysicsImpostor.prototype.getParentsRotation = function () {
  85114. var parent = this.object.parent;
  85115. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  85116. while (parent) {
  85117. if (parent.rotationQuaternion) {
  85118. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  85119. }
  85120. else {
  85121. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  85122. }
  85123. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  85124. parent = parent.parent;
  85125. }
  85126. return this._tmpQuat;
  85127. };
  85128. /**
  85129. * Apply a force
  85130. */
  85131. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  85132. if (this._physicsEngine) {
  85133. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  85134. }
  85135. return this;
  85136. };
  85137. /**
  85138. * Apply an impulse
  85139. */
  85140. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  85141. if (this._physicsEngine) {
  85142. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  85143. }
  85144. return this;
  85145. };
  85146. /**
  85147. * A help function to create a joint.
  85148. */
  85149. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  85150. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  85151. this.addJoint(otherImpostor, joint);
  85152. return this;
  85153. };
  85154. /**
  85155. * Add a joint to this impostor with a different impostor.
  85156. */
  85157. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  85158. this._joints.push({
  85159. otherImpostor: otherImpostor,
  85160. joint: joint
  85161. });
  85162. if (this._physicsEngine) {
  85163. this._physicsEngine.addJoint(this, otherImpostor, joint);
  85164. }
  85165. return this;
  85166. };
  85167. /**
  85168. * Will keep this body still, in a sleep mode.
  85169. */
  85170. PhysicsImpostor.prototype.sleep = function () {
  85171. if (this._physicsEngine) {
  85172. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  85173. }
  85174. return this;
  85175. };
  85176. /**
  85177. * Wake the body up.
  85178. */
  85179. PhysicsImpostor.prototype.wakeUp = function () {
  85180. if (this._physicsEngine) {
  85181. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  85182. }
  85183. return this;
  85184. };
  85185. PhysicsImpostor.prototype.clone = function (newObject) {
  85186. if (!newObject)
  85187. return null;
  85188. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  85189. };
  85190. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  85191. var _this = this;
  85192. //no dispose if no physics engine is available.
  85193. if (!this._physicsEngine) {
  85194. return;
  85195. }
  85196. this._joints.forEach(function (j) {
  85197. if (_this._physicsEngine) {
  85198. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  85199. }
  85200. });
  85201. //dispose the physics body
  85202. this._physicsEngine.removeImpostor(this);
  85203. if (this.parent) {
  85204. this.parent.forceUpdate();
  85205. }
  85206. else {
  85207. /*this._object.getChildMeshes().forEach(function(mesh) {
  85208. if (mesh.physicsImpostor) {
  85209. if (disposeChildren) {
  85210. mesh.physicsImpostor.dispose();
  85211. mesh.physicsImpostor = null;
  85212. }
  85213. }
  85214. })*/
  85215. }
  85216. this._isDisposed = true;
  85217. };
  85218. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  85219. this._deltaPosition.copyFrom(position);
  85220. };
  85221. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  85222. if (!this._deltaRotation) {
  85223. this._deltaRotation = new BABYLON.Quaternion();
  85224. }
  85225. this._deltaRotation.copyFrom(rotation);
  85226. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  85227. };
  85228. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  85229. if (this._physicsEngine) {
  85230. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  85231. }
  85232. return this;
  85233. };
  85234. PhysicsImpostor.prototype.getRadius = function () {
  85235. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  85236. };
  85237. /**
  85238. * Sync a bone with this impostor
  85239. * @param bone The bone to sync to the impostor.
  85240. * @param boneMesh The mesh that the bone is influencing.
  85241. * @param jointPivot The pivot of the joint / bone in local space.
  85242. * @param distToJoint Optional distance from the impostor to the joint.
  85243. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85244. */
  85245. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  85246. var tempVec = PhysicsImpostor._tmpVecs[0];
  85247. var mesh = this.object;
  85248. if (mesh.rotationQuaternion) {
  85249. if (adjustRotation) {
  85250. var tempQuat = PhysicsImpostor._tmpQuat;
  85251. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  85252. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  85253. }
  85254. else {
  85255. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  85256. }
  85257. }
  85258. tempVec.x = 0;
  85259. tempVec.y = 0;
  85260. tempVec.z = 0;
  85261. if (jointPivot) {
  85262. tempVec.x = jointPivot.x;
  85263. tempVec.y = jointPivot.y;
  85264. tempVec.z = jointPivot.z;
  85265. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  85266. if (distToJoint === undefined || distToJoint === null) {
  85267. distToJoint = jointPivot.length();
  85268. }
  85269. tempVec.x *= distToJoint;
  85270. tempVec.y *= distToJoint;
  85271. tempVec.z *= distToJoint;
  85272. }
  85273. if (bone.getParent()) {
  85274. tempVec.addInPlace(mesh.getAbsolutePosition());
  85275. bone.setAbsolutePosition(tempVec, boneMesh);
  85276. }
  85277. else {
  85278. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  85279. boneMesh.position.x -= tempVec.x;
  85280. boneMesh.position.y -= tempVec.y;
  85281. boneMesh.position.z -= tempVec.z;
  85282. }
  85283. };
  85284. /**
  85285. * Sync impostor to a bone
  85286. * @param bone The bone that the impostor will be synced to.
  85287. * @param boneMesh The mesh that the bone is influencing.
  85288. * @param jointPivot The pivot of the joint / bone in local space.
  85289. * @param distToJoint Optional distance from the impostor to the joint.
  85290. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  85291. * @param boneAxis Optional vector3 axis the bone is aligned with
  85292. */
  85293. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  85294. var mesh = this.object;
  85295. if (mesh.rotationQuaternion) {
  85296. if (adjustRotation) {
  85297. var tempQuat = PhysicsImpostor._tmpQuat;
  85298. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85299. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85300. }
  85301. else {
  85302. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85303. }
  85304. }
  85305. var pos = PhysicsImpostor._tmpVecs[0];
  85306. var boneDir = PhysicsImpostor._tmpVecs[1];
  85307. if (!boneAxis) {
  85308. boneAxis = PhysicsImpostor._tmpVecs[2];
  85309. boneAxis.x = 0;
  85310. boneAxis.y = 1;
  85311. boneAxis.z = 0;
  85312. }
  85313. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85314. bone.getAbsolutePositionToRef(boneMesh, pos);
  85315. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85316. distToJoint = jointPivot.length();
  85317. }
  85318. if (distToJoint !== undefined && distToJoint !== null) {
  85319. pos.x += boneDir.x * distToJoint;
  85320. pos.y += boneDir.y * distToJoint;
  85321. pos.z += boneDir.z * distToJoint;
  85322. }
  85323. mesh.setAbsolutePosition(pos);
  85324. };
  85325. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85326. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85327. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85328. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85329. //Impostor types
  85330. PhysicsImpostor.NoImpostor = 0;
  85331. PhysicsImpostor.SphereImpostor = 1;
  85332. PhysicsImpostor.BoxImpostor = 2;
  85333. PhysicsImpostor.PlaneImpostor = 3;
  85334. PhysicsImpostor.MeshImpostor = 4;
  85335. PhysicsImpostor.CylinderImpostor = 7;
  85336. PhysicsImpostor.ParticleImpostor = 8;
  85337. PhysicsImpostor.HeightmapImpostor = 9;
  85338. return PhysicsImpostor;
  85339. }());
  85340. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85341. })(BABYLON || (BABYLON = {}));
  85342. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85343. var BABYLON;
  85344. (function (BABYLON) {
  85345. var PhysicsEngine = /** @class */ (function () {
  85346. function PhysicsEngine(gravity, _physicsPlugin) {
  85347. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85348. this._physicsPlugin = _physicsPlugin;
  85349. //new methods and parameters
  85350. this._impostors = [];
  85351. this._joints = [];
  85352. if (!this._physicsPlugin.isSupported()) {
  85353. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85354. + "Please make sure it is included.");
  85355. }
  85356. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85357. this.setGravity(gravity);
  85358. this.setTimeStep();
  85359. }
  85360. PhysicsEngine.prototype.setGravity = function (gravity) {
  85361. this.gravity = gravity;
  85362. this._physicsPlugin.setGravity(this.gravity);
  85363. };
  85364. /**
  85365. * Set the time step of the physics engine.
  85366. * default is 1/60.
  85367. * To slow it down, enter 1/600 for example.
  85368. * To speed it up, 1/30
  85369. * @param {number} newTimeStep the new timestep to apply to this world.
  85370. */
  85371. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85372. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85373. this._physicsPlugin.setTimeStep(newTimeStep);
  85374. };
  85375. /**
  85376. * Get the time step of the physics engine.
  85377. */
  85378. PhysicsEngine.prototype.getTimeStep = function () {
  85379. return this._physicsPlugin.getTimeStep();
  85380. };
  85381. PhysicsEngine.prototype.dispose = function () {
  85382. this._impostors.forEach(function (impostor) {
  85383. impostor.dispose();
  85384. });
  85385. this._physicsPlugin.dispose();
  85386. };
  85387. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85388. return this._physicsPlugin.name;
  85389. };
  85390. /**
  85391. * Adding a new impostor for the impostor tracking.
  85392. * This will be done by the impostor itself.
  85393. * @param {PhysicsImpostor} impostor the impostor to add
  85394. */
  85395. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85396. impostor.uniqueId = this._impostors.push(impostor);
  85397. //if no parent, generate the body
  85398. if (!impostor.parent) {
  85399. this._physicsPlugin.generatePhysicsBody(impostor);
  85400. }
  85401. };
  85402. /**
  85403. * Remove an impostor from the engine.
  85404. * This impostor and its mesh will not longer be updated by the physics engine.
  85405. * @param {PhysicsImpostor} impostor the impostor to remove
  85406. */
  85407. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85408. var index = this._impostors.indexOf(impostor);
  85409. if (index > -1) {
  85410. var removed = this._impostors.splice(index, 1);
  85411. //Is it needed?
  85412. if (removed.length) {
  85413. //this will also remove it from the world.
  85414. removed[0].physicsBody = null;
  85415. }
  85416. }
  85417. };
  85418. /**
  85419. * Add a joint to the physics engine
  85420. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85421. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85422. * @param {PhysicsJoint} the joint that will connect both impostors.
  85423. */
  85424. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85425. var impostorJoint = {
  85426. mainImpostor: mainImpostor,
  85427. connectedImpostor: connectedImpostor,
  85428. joint: joint
  85429. };
  85430. joint.physicsPlugin = this._physicsPlugin;
  85431. this._joints.push(impostorJoint);
  85432. this._physicsPlugin.generateJoint(impostorJoint);
  85433. };
  85434. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85435. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85436. return (impostorJoint.connectedImpostor === connectedImpostor
  85437. && impostorJoint.joint === joint
  85438. && impostorJoint.mainImpostor === mainImpostor);
  85439. });
  85440. if (matchingJoints.length) {
  85441. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85442. //TODO remove it from the list as well
  85443. }
  85444. };
  85445. /**
  85446. * Called by the scene. no need to call it.
  85447. */
  85448. PhysicsEngine.prototype._step = function (delta) {
  85449. var _this = this;
  85450. //check if any mesh has no body / requires an update
  85451. this._impostors.forEach(function (impostor) {
  85452. if (impostor.isBodyInitRequired()) {
  85453. _this._physicsPlugin.generatePhysicsBody(impostor);
  85454. }
  85455. });
  85456. if (delta > 0.1) {
  85457. delta = 0.1;
  85458. }
  85459. else if (delta <= 0) {
  85460. delta = 1.0 / 60.0;
  85461. }
  85462. this._physicsPlugin.executeStep(delta, this._impostors);
  85463. };
  85464. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85465. return this._physicsPlugin;
  85466. };
  85467. PhysicsEngine.prototype.getImpostors = function () {
  85468. return this._impostors;
  85469. };
  85470. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85471. for (var i = 0; i < this._impostors.length; ++i) {
  85472. if (this._impostors[i].object === object) {
  85473. return this._impostors[i];
  85474. }
  85475. }
  85476. return null;
  85477. };
  85478. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85479. for (var i = 0; i < this._impostors.length; ++i) {
  85480. if (this._impostors[i].physicsBody === body) {
  85481. return this._impostors[i];
  85482. }
  85483. }
  85484. return null;
  85485. };
  85486. // Statics
  85487. PhysicsEngine.Epsilon = 0.001;
  85488. return PhysicsEngine;
  85489. }());
  85490. BABYLON.PhysicsEngine = PhysicsEngine;
  85491. })(BABYLON || (BABYLON = {}));
  85492. //# sourceMappingURL=babylon.physicsEngine.js.map
  85493. var BABYLON;
  85494. (function (BABYLON) {
  85495. var PhysicsHelper = /** @class */ (function () {
  85496. function PhysicsHelper(scene) {
  85497. this._scene = scene;
  85498. this._physicsEngine = this._scene.getPhysicsEngine();
  85499. if (!this._physicsEngine) {
  85500. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85501. }
  85502. }
  85503. /**
  85504. * @param {Vector3} origin the origin of the explosion
  85505. * @param {number} radius the explosion radius
  85506. * @param {number} strength the explosion strength
  85507. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85508. */
  85509. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85510. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85511. if (!this._physicsEngine) {
  85512. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85513. return null;
  85514. }
  85515. var impostors = this._physicsEngine.getImpostors();
  85516. if (impostors.length === 0) {
  85517. return null;
  85518. }
  85519. var event = new PhysicsRadialExplosionEvent(this._scene);
  85520. impostors.forEach(function (impostor) {
  85521. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85522. if (!impostorForceAndContactPoint) {
  85523. return;
  85524. }
  85525. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85526. });
  85527. event.dispose(false);
  85528. return event;
  85529. };
  85530. /**
  85531. * @param {Vector3} origin the origin of the explosion
  85532. * @param {number} radius the explosion radius
  85533. * @param {number} strength the explosion strength
  85534. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85535. */
  85536. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85537. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85538. if (!this._physicsEngine) {
  85539. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85540. return null;
  85541. }
  85542. var impostors = this._physicsEngine.getImpostors();
  85543. if (impostors.length === 0) {
  85544. return null;
  85545. }
  85546. var event = new PhysicsRadialExplosionEvent(this._scene);
  85547. impostors.forEach(function (impostor) {
  85548. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85549. if (!impostorForceAndContactPoint) {
  85550. return;
  85551. }
  85552. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85553. });
  85554. event.dispose(false);
  85555. return event;
  85556. };
  85557. /**
  85558. * @param {Vector3} origin the origin of the explosion
  85559. * @param {number} radius the explosion radius
  85560. * @param {number} strength the explosion strength
  85561. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85562. */
  85563. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85564. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85565. if (!this._physicsEngine) {
  85566. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85567. return null;
  85568. }
  85569. var impostors = this._physicsEngine.getImpostors();
  85570. if (impostors.length === 0) {
  85571. return null;
  85572. }
  85573. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85574. event.dispose(false);
  85575. return event;
  85576. };
  85577. /**
  85578. * @param {Vector3} origin the origin of the updraft
  85579. * @param {number} radius the radius of the updraft
  85580. * @param {number} strength the strength of the updraft
  85581. * @param {number} height the height of the updraft
  85582. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85583. */
  85584. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85585. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85586. if (!this._physicsEngine) {
  85587. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85588. return null;
  85589. }
  85590. if (this._physicsEngine.getImpostors().length === 0) {
  85591. return null;
  85592. }
  85593. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85594. event.dispose(false);
  85595. return event;
  85596. };
  85597. /**
  85598. * @param {Vector3} origin the of the vortex
  85599. * @param {number} radius the radius of the vortex
  85600. * @param {number} strength the strength of the vortex
  85601. * @param {number} height the height of the vortex
  85602. */
  85603. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85604. if (!this._physicsEngine) {
  85605. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85606. return null;
  85607. }
  85608. if (this._physicsEngine.getImpostors().length === 0) {
  85609. return null;
  85610. }
  85611. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85612. event.dispose(false);
  85613. return event;
  85614. };
  85615. return PhysicsHelper;
  85616. }());
  85617. BABYLON.PhysicsHelper = PhysicsHelper;
  85618. /***** Radial explosion *****/
  85619. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85620. function PhysicsRadialExplosionEvent(scene) {
  85621. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85622. this._rays = [];
  85623. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85624. this._scene = scene;
  85625. }
  85626. /**
  85627. * Returns the data related to the radial explosion event (sphere & rays).
  85628. * @returns {PhysicsRadialExplosionEventData}
  85629. */
  85630. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85631. this._dataFetched = true;
  85632. return {
  85633. sphere: this._sphere,
  85634. rays: this._rays,
  85635. };
  85636. };
  85637. /**
  85638. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85639. * @param impostor
  85640. * @param {Vector3} origin the origin of the explosion
  85641. * @param {number} radius the explosion radius
  85642. * @param {number} strength the explosion strength
  85643. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85644. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85645. */
  85646. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85647. if (impostor.mass === 0) {
  85648. return null;
  85649. }
  85650. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85651. return null;
  85652. }
  85653. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85654. return null;
  85655. }
  85656. var impostorObjectCenter = impostor.getObjectCenter();
  85657. var direction = impostorObjectCenter.subtract(origin);
  85658. var ray = new BABYLON.Ray(origin, direction, radius);
  85659. this._rays.push(ray);
  85660. var hit = ray.intersectsMesh(impostor.object);
  85661. var contactPoint = hit.pickedPoint;
  85662. if (!contactPoint) {
  85663. return null;
  85664. }
  85665. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85666. if (distanceFromOrigin > radius) {
  85667. return null;
  85668. }
  85669. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85670. ? strength
  85671. : strength * (1 - (distanceFromOrigin / radius));
  85672. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85673. return { force: force, contactPoint: contactPoint };
  85674. };
  85675. /**
  85676. * Disposes the sphere.
  85677. * @param {bolean} force
  85678. */
  85679. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85680. var _this = this;
  85681. if (force === void 0) { force = true; }
  85682. if (force) {
  85683. this._sphere.dispose();
  85684. }
  85685. else {
  85686. setTimeout(function () {
  85687. if (!_this._dataFetched) {
  85688. _this._sphere.dispose();
  85689. }
  85690. }, 0);
  85691. }
  85692. };
  85693. /*** Helpers ***/
  85694. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85695. if (!this._sphere) {
  85696. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85697. this._sphere.isVisible = false;
  85698. }
  85699. };
  85700. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85701. var impostorObject = impostor.object;
  85702. this._prepareSphere();
  85703. this._sphere.position = origin;
  85704. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85705. this._sphere._updateBoundingInfo();
  85706. this._sphere.computeWorldMatrix(true);
  85707. return this._sphere.intersectsMesh(impostorObject, true);
  85708. };
  85709. return PhysicsRadialExplosionEvent;
  85710. }());
  85711. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85712. /***** Gravitational Field *****/
  85713. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85714. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85715. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85716. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85717. this._physicsHelper = physicsHelper;
  85718. this._scene = scene;
  85719. this._origin = origin;
  85720. this._radius = radius;
  85721. this._strength = strength;
  85722. this._falloff = falloff;
  85723. this._tickCallback = this._tick.bind(this);
  85724. }
  85725. /**
  85726. * Returns the data related to the gravitational field event (sphere).
  85727. * @returns {PhysicsGravitationalFieldEventData}
  85728. */
  85729. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85730. this._dataFetched = true;
  85731. return {
  85732. sphere: this._sphere,
  85733. };
  85734. };
  85735. /**
  85736. * Enables the gravitational field.
  85737. */
  85738. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85739. this._tickCallback.call(this);
  85740. this._scene.registerBeforeRender(this._tickCallback);
  85741. };
  85742. /**
  85743. * Disables the gravitational field.
  85744. */
  85745. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85746. this._scene.unregisterBeforeRender(this._tickCallback);
  85747. };
  85748. /**
  85749. * Disposes the sphere.
  85750. * @param {bolean} force
  85751. */
  85752. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85753. var _this = this;
  85754. if (force === void 0) { force = true; }
  85755. if (force) {
  85756. this._sphere.dispose();
  85757. }
  85758. else {
  85759. setTimeout(function () {
  85760. if (!_this._dataFetched) {
  85761. _this._sphere.dispose();
  85762. }
  85763. }, 0);
  85764. }
  85765. };
  85766. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85767. // Since the params won't change, we fetch the event only once
  85768. if (this._sphere) {
  85769. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85770. }
  85771. else {
  85772. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85773. if (radialExplosionEvent) {
  85774. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85775. }
  85776. }
  85777. };
  85778. return PhysicsGravitationalFieldEvent;
  85779. }());
  85780. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85781. /***** Updraft *****/
  85782. var PhysicsUpdraftEvent = /** @class */ (function () {
  85783. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85784. this._scene = _scene;
  85785. this._origin = _origin;
  85786. this._radius = _radius;
  85787. this._strength = _strength;
  85788. this._height = _height;
  85789. this._updraftMode = _updraftMode;
  85790. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85791. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85792. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85793. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85794. this._physicsEngine = this._scene.getPhysicsEngine();
  85795. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85796. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85797. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85798. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85799. }
  85800. this._tickCallback = this._tick.bind(this);
  85801. }
  85802. /**
  85803. * Returns the data related to the updraft event (cylinder).
  85804. * @returns {PhysicsUpdraftEventData}
  85805. */
  85806. PhysicsUpdraftEvent.prototype.getData = function () {
  85807. this._dataFetched = true;
  85808. return {
  85809. cylinder: this._cylinder,
  85810. };
  85811. };
  85812. /**
  85813. * Enables the updraft.
  85814. */
  85815. PhysicsUpdraftEvent.prototype.enable = function () {
  85816. this._tickCallback.call(this);
  85817. this._scene.registerBeforeRender(this._tickCallback);
  85818. };
  85819. /**
  85820. * Disables the cortex.
  85821. */
  85822. PhysicsUpdraftEvent.prototype.disable = function () {
  85823. this._scene.unregisterBeforeRender(this._tickCallback);
  85824. };
  85825. /**
  85826. * Disposes the sphere.
  85827. * @param {bolean} force
  85828. */
  85829. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85830. var _this = this;
  85831. if (force === void 0) { force = true; }
  85832. if (force) {
  85833. this._cylinder.dispose();
  85834. }
  85835. else {
  85836. setTimeout(function () {
  85837. if (!_this._dataFetched) {
  85838. _this._cylinder.dispose();
  85839. }
  85840. }, 0);
  85841. }
  85842. };
  85843. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85844. if (impostor.mass === 0) {
  85845. return null;
  85846. }
  85847. if (!this._intersectsWithCylinder(impostor)) {
  85848. return null;
  85849. }
  85850. var impostorObjectCenter = impostor.getObjectCenter();
  85851. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85852. var direction = this._originDirection;
  85853. }
  85854. else {
  85855. var direction = impostorObjectCenter.subtract(this._originTop);
  85856. }
  85857. var multiplier = this._strength * -1;
  85858. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85859. return { force: force, contactPoint: impostorObjectCenter };
  85860. };
  85861. PhysicsUpdraftEvent.prototype._tick = function () {
  85862. var _this = this;
  85863. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85864. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85865. if (!impostorForceAndContactPoint) {
  85866. return;
  85867. }
  85868. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85869. });
  85870. };
  85871. /*** Helpers ***/
  85872. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85873. if (!this._cylinder) {
  85874. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85875. height: this._height,
  85876. diameter: this._radius * 2,
  85877. }, this._scene);
  85878. this._cylinder.isVisible = false;
  85879. }
  85880. };
  85881. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85882. var impostorObject = impostor.object;
  85883. this._prepareCylinder();
  85884. this._cylinder.position = this._cylinderPosition;
  85885. return this._cylinder.intersectsMesh(impostorObject, true);
  85886. };
  85887. return PhysicsUpdraftEvent;
  85888. }());
  85889. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85890. /***** Vortex *****/
  85891. var PhysicsVortexEvent = /** @class */ (function () {
  85892. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85893. this._scene = _scene;
  85894. this._origin = _origin;
  85895. this._radius = _radius;
  85896. this._strength = _strength;
  85897. this._height = _height;
  85898. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85899. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85900. this._updraftMultiplier = 0.02;
  85901. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85902. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85903. this._physicsEngine = this._scene.getPhysicsEngine();
  85904. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85905. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85906. this._tickCallback = this._tick.bind(this);
  85907. }
  85908. /**
  85909. * Returns the data related to the vortex event (cylinder).
  85910. * @returns {PhysicsVortexEventData}
  85911. */
  85912. PhysicsVortexEvent.prototype.getData = function () {
  85913. this._dataFetched = true;
  85914. return {
  85915. cylinder: this._cylinder,
  85916. };
  85917. };
  85918. /**
  85919. * Enables the vortex.
  85920. */
  85921. PhysicsVortexEvent.prototype.enable = function () {
  85922. this._tickCallback.call(this);
  85923. this._scene.registerBeforeRender(this._tickCallback);
  85924. };
  85925. /**
  85926. * Disables the cortex.
  85927. */
  85928. PhysicsVortexEvent.prototype.disable = function () {
  85929. this._scene.unregisterBeforeRender(this._tickCallback);
  85930. };
  85931. /**
  85932. * Disposes the sphere.
  85933. * @param {bolean} force
  85934. */
  85935. PhysicsVortexEvent.prototype.dispose = function (force) {
  85936. var _this = this;
  85937. if (force === void 0) { force = true; }
  85938. if (force) {
  85939. this._cylinder.dispose();
  85940. }
  85941. else {
  85942. setTimeout(function () {
  85943. if (!_this._dataFetched) {
  85944. _this._cylinder.dispose();
  85945. }
  85946. }, 0);
  85947. }
  85948. };
  85949. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85950. if (impostor.mass === 0) {
  85951. return null;
  85952. }
  85953. if (!this._intersectsWithCylinder(impostor)) {
  85954. return null;
  85955. }
  85956. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85957. return null;
  85958. }
  85959. var impostorObjectCenter = impostor.getObjectCenter();
  85960. 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)
  85961. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85962. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85963. var hit = ray.intersectsMesh(impostor.object);
  85964. var contactPoint = hit.pickedPoint;
  85965. if (!contactPoint) {
  85966. return null;
  85967. }
  85968. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85969. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85970. var directionToOrigin = contactPoint.normalize();
  85971. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85972. directionToOrigin = directionToOrigin.negate();
  85973. }
  85974. // TODO: find a more physically based solution
  85975. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85976. var forceX = directionToOrigin.x * this._strength / 8;
  85977. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85978. var forceZ = directionToOrigin.z * this._strength / 8;
  85979. }
  85980. else {
  85981. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85982. var forceY = this._originTop.y * this._updraftMultiplier;
  85983. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85984. }
  85985. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85986. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85987. return { force: force, contactPoint: impostorObjectCenter };
  85988. };
  85989. PhysicsVortexEvent.prototype._tick = function () {
  85990. var _this = this;
  85991. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85992. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85993. if (!impostorForceAndContactPoint) {
  85994. return;
  85995. }
  85996. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85997. });
  85998. };
  85999. /*** Helpers ***/
  86000. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  86001. if (!this._cylinder) {
  86002. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  86003. height: this._height,
  86004. diameter: this._radius * 2,
  86005. }, this._scene);
  86006. this._cylinder.isVisible = false;
  86007. }
  86008. };
  86009. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  86010. var impostorObject = impostor.object;
  86011. this._prepareCylinder();
  86012. this._cylinder.position = this._cylinderPosition;
  86013. return this._cylinder.intersectsMesh(impostorObject, true);
  86014. };
  86015. return PhysicsVortexEvent;
  86016. }());
  86017. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  86018. /***** Enums *****/
  86019. /**
  86020. * The strenght of the force in correspondence to the distance of the affected object
  86021. */
  86022. var PhysicsRadialImpulseFalloff;
  86023. (function (PhysicsRadialImpulseFalloff) {
  86024. /** Defines that impulse is constant in strength across it's whole radius */
  86025. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  86026. /** DEfines that impulse gets weaker if it's further from the origin */
  86027. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  86028. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  86029. /**
  86030. * The strenght of the force in correspondence to the distance of the affected object
  86031. */
  86032. var PhysicsUpdraftMode;
  86033. (function (PhysicsUpdraftMode) {
  86034. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  86035. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  86036. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  86037. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  86038. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  86039. })(BABYLON || (BABYLON = {}));
  86040. //# sourceMappingURL=babylon.physicsHelper.js.map
  86041. var BABYLON;
  86042. (function (BABYLON) {
  86043. var CannonJSPlugin = /** @class */ (function () {
  86044. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  86045. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  86046. if (iterations === void 0) { iterations = 10; }
  86047. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  86048. this.name = "CannonJSPlugin";
  86049. this._physicsMaterials = new Array();
  86050. this._fixedTimeStep = 1 / 60;
  86051. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  86052. this.BJSCANNON = CANNON;
  86053. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  86054. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  86055. this._tmpPosition = BABYLON.Vector3.Zero();
  86056. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  86057. this._tmpUnityRotation = new BABYLON.Quaternion();
  86058. if (!this.isSupported()) {
  86059. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  86060. return;
  86061. }
  86062. this._extendNamespace();
  86063. this.world = new this.BJSCANNON.World();
  86064. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  86065. this.world.solver.iterations = iterations;
  86066. }
  86067. CannonJSPlugin.prototype.setGravity = function (gravity) {
  86068. this.world.gravity.copy(gravity);
  86069. };
  86070. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  86071. this._fixedTimeStep = timeStep;
  86072. };
  86073. CannonJSPlugin.prototype.getTimeStep = function () {
  86074. return this._fixedTimeStep;
  86075. };
  86076. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  86077. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  86078. };
  86079. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86080. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86081. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86082. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  86083. };
  86084. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86085. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  86086. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  86087. impostor.physicsBody.applyForce(impulse, worldPoint);
  86088. };
  86089. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86090. //parent-child relationship. Does this impostor has a parent impostor?
  86091. if (impostor.parent) {
  86092. if (impostor.physicsBody) {
  86093. this.removePhysicsBody(impostor);
  86094. //TODO is that needed?
  86095. impostor.forceUpdate();
  86096. }
  86097. return;
  86098. }
  86099. //should a new body be created for this impostor?
  86100. if (impostor.isBodyInitRequired()) {
  86101. var shape = this._createShape(impostor);
  86102. //unregister events, if body is being changed
  86103. var oldBody = impostor.physicsBody;
  86104. if (oldBody) {
  86105. this.removePhysicsBody(impostor);
  86106. }
  86107. //create the body and material
  86108. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  86109. var bodyCreationObject = {
  86110. mass: impostor.getParam("mass"),
  86111. material: material
  86112. };
  86113. // A simple extend, in case native options were used.
  86114. var nativeOptions = impostor.getParam("nativeOptions");
  86115. for (var key in nativeOptions) {
  86116. if (nativeOptions.hasOwnProperty(key)) {
  86117. bodyCreationObject[key] = nativeOptions[key];
  86118. }
  86119. }
  86120. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  86121. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  86122. this.world.addEventListener("preStep", impostor.beforeStep);
  86123. this.world.addEventListener("postStep", impostor.afterStep);
  86124. impostor.physicsBody.addShape(shape);
  86125. this.world.add(impostor.physicsBody);
  86126. //try to keep the body moving in the right direction by taking old properties.
  86127. //Should be tested!
  86128. if (oldBody) {
  86129. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  86130. impostor.physicsBody[param].copy(oldBody[param]);
  86131. });
  86132. }
  86133. this._processChildMeshes(impostor);
  86134. }
  86135. //now update the body's transformation
  86136. this._updatePhysicsBodyTransformation(impostor);
  86137. };
  86138. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  86139. var _this = this;
  86140. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  86141. var currentRotation = mainImpostor.object.rotationQuaternion;
  86142. if (meshChildren.length) {
  86143. var processMesh = function (localPosition, mesh) {
  86144. if (!currentRotation || !mesh.rotationQuaternion) {
  86145. return;
  86146. }
  86147. var childImpostor = mesh.getPhysicsImpostor();
  86148. if (childImpostor) {
  86149. var parent = childImpostor.parent;
  86150. if (parent !== mainImpostor) {
  86151. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  86152. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  86153. if (childImpostor.physicsBody) {
  86154. _this.removePhysicsBody(childImpostor);
  86155. childImpostor.physicsBody = null;
  86156. }
  86157. childImpostor.parent = mainImpostor;
  86158. childImpostor.resetUpdateFlags();
  86159. 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));
  86160. //Add the mass of the children.
  86161. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  86162. }
  86163. }
  86164. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  86165. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  86166. };
  86167. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  86168. }
  86169. };
  86170. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86171. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  86172. this.world.removeEventListener("preStep", impostor.beforeStep);
  86173. this.world.removeEventListener("postStep", impostor.afterStep);
  86174. this.world.remove(impostor.physicsBody);
  86175. };
  86176. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86177. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86178. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86179. if (!mainBody || !connectedBody) {
  86180. return;
  86181. }
  86182. var constraint;
  86183. var jointData = impostorJoint.joint.jointData;
  86184. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  86185. var constraintData = {
  86186. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  86187. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  86188. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  86189. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  86190. maxForce: jointData.nativeParams.maxForce,
  86191. collideConnected: !!jointData.collision
  86192. };
  86193. switch (impostorJoint.joint.type) {
  86194. case BABYLON.PhysicsJoint.HingeJoint:
  86195. case BABYLON.PhysicsJoint.Hinge2Joint:
  86196. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  86197. break;
  86198. case BABYLON.PhysicsJoint.DistanceJoint:
  86199. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  86200. break;
  86201. case BABYLON.PhysicsJoint.SpringJoint:
  86202. var springData = jointData;
  86203. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  86204. restLength: springData.length,
  86205. stiffness: springData.stiffness,
  86206. damping: springData.damping,
  86207. localAnchorA: constraintData.pivotA,
  86208. localAnchorB: constraintData.pivotB
  86209. });
  86210. break;
  86211. case BABYLON.PhysicsJoint.LockJoint:
  86212. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  86213. break;
  86214. case BABYLON.PhysicsJoint.PointToPointJoint:
  86215. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86216. default:
  86217. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  86218. break;
  86219. }
  86220. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  86221. constraint.collideConnected = !!jointData.collision;
  86222. impostorJoint.joint.physicsJoint = constraint;
  86223. //don't add spring as constraint, as it is not one.
  86224. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  86225. this.world.addConstraint(constraint);
  86226. }
  86227. else {
  86228. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  86229. constraint.applyForce();
  86230. });
  86231. }
  86232. };
  86233. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86234. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  86235. };
  86236. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  86237. var index;
  86238. var mat;
  86239. for (index = 0; index < this._physicsMaterials.length; index++) {
  86240. mat = this._physicsMaterials[index];
  86241. if (mat.friction === friction && mat.restitution === restitution) {
  86242. return mat;
  86243. }
  86244. }
  86245. var currentMat = new this.BJSCANNON.Material(name);
  86246. currentMat.friction = friction;
  86247. currentMat.restitution = restitution;
  86248. this._physicsMaterials.push(currentMat);
  86249. return currentMat;
  86250. };
  86251. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  86252. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  86253. };
  86254. CannonJSPlugin.prototype._createShape = function (impostor) {
  86255. var object = impostor.object;
  86256. var returnValue;
  86257. var extendSize = impostor.getObjectExtendSize();
  86258. switch (impostor.type) {
  86259. case BABYLON.PhysicsImpostor.SphereImpostor:
  86260. var radiusX = extendSize.x;
  86261. var radiusY = extendSize.y;
  86262. var radiusZ = extendSize.z;
  86263. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  86264. break;
  86265. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  86266. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86267. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  86268. break;
  86269. case BABYLON.PhysicsImpostor.BoxImpostor:
  86270. var box = extendSize.scale(0.5);
  86271. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  86272. break;
  86273. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86274. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  86275. returnValue = new this.BJSCANNON.Plane();
  86276. break;
  86277. case BABYLON.PhysicsImpostor.MeshImpostor:
  86278. // should transform the vertex data to world coordinates!!
  86279. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  86280. var rawFaces = object.getIndices ? object.getIndices() : [];
  86281. if (!rawVerts)
  86282. return;
  86283. // get only scale! so the object could transform correctly.
  86284. var oldPosition = object.position.clone();
  86285. var oldRotation = object.rotation && object.rotation.clone();
  86286. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  86287. object.position.copyFromFloats(0, 0, 0);
  86288. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86289. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86290. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86291. var transform = object.computeWorldMatrix(true);
  86292. // convert rawVerts to object space
  86293. var temp = new Array();
  86294. var index;
  86295. for (index = 0; index < rawVerts.length; index += 3) {
  86296. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86297. }
  86298. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86299. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86300. //now set back the transformation!
  86301. object.position.copyFrom(oldPosition);
  86302. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86303. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86304. break;
  86305. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86306. var oldPosition2 = object.position.clone();
  86307. var oldRotation2 = object.rotation && object.rotation.clone();
  86308. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86309. object.position.copyFromFloats(0, 0, 0);
  86310. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86311. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86312. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86313. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86314. returnValue = this._createHeightmap(object);
  86315. object.position.copyFrom(oldPosition2);
  86316. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86317. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86318. object.computeWorldMatrix(true);
  86319. break;
  86320. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86321. returnValue = new this.BJSCANNON.Particle();
  86322. break;
  86323. }
  86324. return returnValue;
  86325. };
  86326. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86327. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86328. var transform = object.computeWorldMatrix(true);
  86329. // convert rawVerts to object space
  86330. var temp = new Array();
  86331. var index;
  86332. for (index = 0; index < pos.length; index += 3) {
  86333. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86334. }
  86335. pos = temp;
  86336. var matrix = new Array();
  86337. //For now pointDepth will not be used and will be automatically calculated.
  86338. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86339. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86340. var boundingInfo = object.getBoundingInfo();
  86341. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86342. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86343. var elementSize = dim * 2 / arraySize;
  86344. for (var i = 0; i < pos.length; i = i + 3) {
  86345. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86346. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86347. var y = -pos[i + 2] + minY;
  86348. if (!matrix[x]) {
  86349. matrix[x] = [];
  86350. }
  86351. if (!matrix[x][z]) {
  86352. matrix[x][z] = y;
  86353. }
  86354. matrix[x][z] = Math.max(y, matrix[x][z]);
  86355. }
  86356. for (var x = 0; x <= arraySize; ++x) {
  86357. if (!matrix[x]) {
  86358. var loc = 1;
  86359. while (!matrix[(x + loc) % arraySize]) {
  86360. loc++;
  86361. }
  86362. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86363. //console.log("missing x", x);
  86364. }
  86365. for (var z = 0; z <= arraySize; ++z) {
  86366. if (!matrix[x][z]) {
  86367. var loc = 1;
  86368. var newValue;
  86369. while (newValue === undefined) {
  86370. newValue = matrix[x][(z + loc++) % arraySize];
  86371. }
  86372. matrix[x][z] = newValue;
  86373. }
  86374. }
  86375. }
  86376. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86377. elementSize: elementSize
  86378. });
  86379. //For future reference, needed for body transformation
  86380. shape.minY = minY;
  86381. return shape;
  86382. };
  86383. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86384. var object = impostor.object;
  86385. //make sure it is updated...
  86386. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86387. // The delta between the mesh position and the mesh bounding box center
  86388. var bInfo = object.getBoundingInfo();
  86389. if (!bInfo)
  86390. return;
  86391. var center = impostor.getObjectCenter();
  86392. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86393. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86394. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86395. this._tmpPosition.copyFrom(center);
  86396. var quaternion = object.rotationQuaternion;
  86397. if (!quaternion) {
  86398. return;
  86399. }
  86400. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86401. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86402. //-90 DEG in X, precalculated
  86403. quaternion = quaternion.multiply(this._minus90X);
  86404. //Invert! (Precalculated, 90 deg in X)
  86405. //No need to clone. this will never change.
  86406. impostor.setDeltaRotation(this._plus90X);
  86407. }
  86408. //If it is a heightfield, if should be centered.
  86409. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86410. var mesh = object;
  86411. var boundingInfo = mesh.getBoundingInfo();
  86412. //calculate the correct body position:
  86413. var rotationQuaternion = mesh.rotationQuaternion;
  86414. mesh.rotationQuaternion = this._tmpUnityRotation;
  86415. mesh.computeWorldMatrix(true);
  86416. //get original center with no rotation
  86417. var c = center.clone();
  86418. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86419. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86420. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86421. mesh.setPreTransformMatrix(p);
  86422. mesh.computeWorldMatrix(true);
  86423. //calculate the translation
  86424. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86425. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86426. //add it inverted to the delta
  86427. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86428. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86429. //rotation is back
  86430. mesh.rotationQuaternion = rotationQuaternion;
  86431. mesh.setPreTransformMatrix(oldPivot);
  86432. mesh.computeWorldMatrix(true);
  86433. }
  86434. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86435. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86436. //this._tmpPosition.copyFrom(object.position);
  86437. }
  86438. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86439. //Now update the impostor object
  86440. impostor.physicsBody.position.copy(this._tmpPosition);
  86441. impostor.physicsBody.quaternion.copy(quaternion);
  86442. };
  86443. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86444. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86445. if (impostor.object.rotationQuaternion) {
  86446. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86447. }
  86448. };
  86449. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86450. impostor.physicsBody.position.copy(newPosition);
  86451. impostor.physicsBody.quaternion.copy(newRotation);
  86452. };
  86453. CannonJSPlugin.prototype.isSupported = function () {
  86454. return this.BJSCANNON !== undefined;
  86455. };
  86456. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86457. impostor.physicsBody.velocity.copy(velocity);
  86458. };
  86459. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86460. impostor.physicsBody.angularVelocity.copy(velocity);
  86461. };
  86462. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86463. var v = impostor.physicsBody.velocity;
  86464. if (!v) {
  86465. return null;
  86466. }
  86467. return new BABYLON.Vector3(v.x, v.y, v.z);
  86468. };
  86469. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86470. var v = impostor.physicsBody.angularVelocity;
  86471. if (!v) {
  86472. return null;
  86473. }
  86474. return new BABYLON.Vector3(v.x, v.y, v.z);
  86475. };
  86476. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86477. impostor.physicsBody.mass = mass;
  86478. impostor.physicsBody.updateMassProperties();
  86479. };
  86480. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86481. return impostor.physicsBody.mass;
  86482. };
  86483. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86484. return impostor.physicsBody.material.friction;
  86485. };
  86486. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86487. impostor.physicsBody.material.friction = friction;
  86488. };
  86489. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86490. return impostor.physicsBody.material.restitution;
  86491. };
  86492. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86493. impostor.physicsBody.material.restitution = restitution;
  86494. };
  86495. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86496. impostor.physicsBody.sleep();
  86497. };
  86498. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86499. impostor.physicsBody.wakeUp();
  86500. };
  86501. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86502. joint.physicsJoint.distance = maxDistance;
  86503. };
  86504. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86505. // if (!motorIndex) {
  86506. // joint.physicsJoint.enableMotor();
  86507. // }
  86508. // }
  86509. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86510. // if (!motorIndex) {
  86511. // joint.physicsJoint.disableMotor();
  86512. // }
  86513. // }
  86514. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86515. if (!motorIndex) {
  86516. joint.physicsJoint.enableMotor();
  86517. joint.physicsJoint.setMotorSpeed(speed);
  86518. if (maxForce) {
  86519. this.setLimit(joint, maxForce);
  86520. }
  86521. }
  86522. };
  86523. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86524. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86525. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86526. };
  86527. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86528. var body = impostor.physicsBody;
  86529. mesh.position.x = body.position.x;
  86530. mesh.position.y = body.position.y;
  86531. mesh.position.z = body.position.z;
  86532. if (mesh.rotationQuaternion) {
  86533. mesh.rotationQuaternion.x = body.quaternion.x;
  86534. mesh.rotationQuaternion.y = body.quaternion.y;
  86535. mesh.rotationQuaternion.z = body.quaternion.z;
  86536. mesh.rotationQuaternion.w = body.quaternion.w;
  86537. }
  86538. };
  86539. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86540. var shape = impostor.physicsBody.shapes[0];
  86541. return shape.boundingSphereRadius;
  86542. };
  86543. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86544. var shape = impostor.physicsBody.shapes[0];
  86545. result.x = shape.halfExtents.x * 2;
  86546. result.y = shape.halfExtents.y * 2;
  86547. result.z = shape.halfExtents.z * 2;
  86548. };
  86549. CannonJSPlugin.prototype.dispose = function () {
  86550. };
  86551. CannonJSPlugin.prototype._extendNamespace = function () {
  86552. //this will force cannon to execute at least one step when using interpolation
  86553. var step_tmp1 = new this.BJSCANNON.Vec3();
  86554. var Engine = this.BJSCANNON;
  86555. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86556. maxSubSteps = maxSubSteps || 10;
  86557. timeSinceLastCalled = timeSinceLastCalled || 0;
  86558. if (timeSinceLastCalled === 0) {
  86559. this.internalStep(dt);
  86560. this.time += dt;
  86561. }
  86562. else {
  86563. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86564. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86565. var t0 = performance.now();
  86566. for (var i = 0; i !== internalSteps; i++) {
  86567. this.internalStep(dt);
  86568. if (performance.now() - t0 > dt * 1000) {
  86569. break;
  86570. }
  86571. }
  86572. this.time += timeSinceLastCalled;
  86573. var h = this.time % dt;
  86574. var h_div_dt = h / dt;
  86575. var interpvelo = step_tmp1;
  86576. var bodies = this.bodies;
  86577. for (var j = 0; j !== bodies.length; j++) {
  86578. var b = bodies[j];
  86579. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86580. b.position.vsub(b.previousPosition, interpvelo);
  86581. interpvelo.scale(h_div_dt, interpvelo);
  86582. b.position.vadd(interpvelo, b.interpolatedPosition);
  86583. }
  86584. else {
  86585. b.interpolatedPosition.copy(b.position);
  86586. b.interpolatedQuaternion.copy(b.quaternion);
  86587. }
  86588. }
  86589. }
  86590. };
  86591. };
  86592. return CannonJSPlugin;
  86593. }());
  86594. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86595. })(BABYLON || (BABYLON = {}));
  86596. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86597. var BABYLON;
  86598. (function (BABYLON) {
  86599. var OimoJSPlugin = /** @class */ (function () {
  86600. function OimoJSPlugin(iterations) {
  86601. this.name = "OimoJSPlugin";
  86602. this._tmpImpostorsArray = [];
  86603. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86604. this.BJSOIMO = OIMO;
  86605. this.world = new this.BJSOIMO.World({
  86606. iterations: iterations
  86607. });
  86608. this.world.clear();
  86609. }
  86610. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86611. this.world.gravity.copy(gravity);
  86612. };
  86613. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86614. this.world.timeStep = timeStep;
  86615. };
  86616. OimoJSPlugin.prototype.getTimeStep = function () {
  86617. return this.world.timeStep;
  86618. };
  86619. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86620. var _this = this;
  86621. impostors.forEach(function (impostor) {
  86622. impostor.beforeStep();
  86623. });
  86624. this.world.step();
  86625. impostors.forEach(function (impostor) {
  86626. impostor.afterStep();
  86627. //update the ordered impostors array
  86628. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86629. });
  86630. //check for collisions
  86631. var contact = this.world.contacts;
  86632. while (contact !== null) {
  86633. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86634. contact = contact.next;
  86635. continue;
  86636. }
  86637. //is this body colliding with any other? get the impostor
  86638. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86639. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86640. if (!mainImpostor || !collidingImpostor) {
  86641. contact = contact.next;
  86642. continue;
  86643. }
  86644. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86645. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86646. contact = contact.next;
  86647. }
  86648. };
  86649. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86650. var mass = impostor.physicsBody.mass;
  86651. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86652. };
  86653. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86654. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86655. this.applyImpulse(impostor, force, contactPoint);
  86656. };
  86657. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86658. var _this = this;
  86659. //parent-child relationship. Does this impostor has a parent impostor?
  86660. if (impostor.parent) {
  86661. if (impostor.physicsBody) {
  86662. this.removePhysicsBody(impostor);
  86663. //TODO is that needed?
  86664. impostor.forceUpdate();
  86665. }
  86666. return;
  86667. }
  86668. if (impostor.isBodyInitRequired()) {
  86669. var bodyConfig = {
  86670. name: impostor.uniqueId,
  86671. //Oimo must have mass, also for static objects.
  86672. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86673. size: [],
  86674. type: [],
  86675. pos: [],
  86676. posShape: [],
  86677. rot: [],
  86678. rotShape: [],
  86679. move: impostor.getParam("mass") !== 0,
  86680. density: impostor.getParam("mass"),
  86681. friction: impostor.getParam("friction"),
  86682. restitution: impostor.getParam("restitution"),
  86683. //Supporting older versions of Oimo
  86684. world: this.world
  86685. };
  86686. var impostors = [impostor];
  86687. var addToArray = function (parent) {
  86688. if (!parent.getChildMeshes)
  86689. return;
  86690. parent.getChildMeshes().forEach(function (m) {
  86691. if (m.physicsImpostor) {
  86692. impostors.push(m.physicsImpostor);
  86693. //m.physicsImpostor._init();
  86694. }
  86695. });
  86696. };
  86697. addToArray(impostor.object);
  86698. var checkWithEpsilon_1 = function (value) {
  86699. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86700. };
  86701. impostors.forEach(function (i) {
  86702. if (!i.object.rotationQuaternion) {
  86703. return;
  86704. }
  86705. //get the correct bounding box
  86706. var oldQuaternion = i.object.rotationQuaternion;
  86707. var rot = oldQuaternion.toEulerAngles();
  86708. var extendSize = i.getObjectExtendSize();
  86709. var radToDeg = 57.295779513082320876;
  86710. if (i === impostor) {
  86711. var center = impostor.getObjectCenter();
  86712. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86713. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86714. //Can also use Array.prototype.push.apply
  86715. bodyConfig.pos.push(center.x);
  86716. bodyConfig.pos.push(center.y);
  86717. bodyConfig.pos.push(center.z);
  86718. bodyConfig.posShape.push(0, 0, 0);
  86719. //tmp solution
  86720. bodyConfig.rot.push(rot.x * radToDeg);
  86721. bodyConfig.rot.push(rot.y * radToDeg);
  86722. bodyConfig.rot.push(rot.z * radToDeg);
  86723. bodyConfig.rotShape.push(0, 0, 0);
  86724. }
  86725. else {
  86726. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86727. bodyConfig.posShape.push(localPosition.x);
  86728. bodyConfig.posShape.push(localPosition.y);
  86729. bodyConfig.posShape.push(localPosition.z);
  86730. bodyConfig.pos.push(0, 0, 0);
  86731. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86732. bodyConfig.rot.push(0);
  86733. bodyConfig.rot.push(0);
  86734. bodyConfig.rot.push(0);
  86735. bodyConfig.rotShape.push(rot.x * radToDeg);
  86736. bodyConfig.rotShape.push(rot.y * radToDeg);
  86737. bodyConfig.rotShape.push(rot.z * radToDeg);
  86738. }
  86739. // register mesh
  86740. switch (i.type) {
  86741. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86742. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86743. case BABYLON.PhysicsImpostor.SphereImpostor:
  86744. var radiusX = extendSize.x;
  86745. var radiusY = extendSize.y;
  86746. var radiusZ = extendSize.z;
  86747. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86748. bodyConfig.type.push('sphere');
  86749. //due to the way oimo works with compounds, add 3 times
  86750. bodyConfig.size.push(size);
  86751. bodyConfig.size.push(size);
  86752. bodyConfig.size.push(size);
  86753. break;
  86754. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86755. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86756. var sizeY = checkWithEpsilon_1(extendSize.y);
  86757. bodyConfig.type.push('cylinder');
  86758. bodyConfig.size.push(sizeX);
  86759. bodyConfig.size.push(sizeY);
  86760. //due to the way oimo works with compounds, add one more value.
  86761. bodyConfig.size.push(sizeY);
  86762. break;
  86763. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86764. case BABYLON.PhysicsImpostor.BoxImpostor:
  86765. default:
  86766. var sizeX = checkWithEpsilon_1(extendSize.x);
  86767. var sizeY = checkWithEpsilon_1(extendSize.y);
  86768. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86769. bodyConfig.type.push('box');
  86770. //if (i === impostor) {
  86771. bodyConfig.size.push(sizeX);
  86772. bodyConfig.size.push(sizeY);
  86773. bodyConfig.size.push(sizeZ);
  86774. //} else {
  86775. // bodyConfig.size.push(0,0,0);
  86776. //}
  86777. break;
  86778. }
  86779. //actually not needed, but hey...
  86780. i.object.rotationQuaternion = oldQuaternion;
  86781. });
  86782. impostor.physicsBody = this.world.add(bodyConfig);
  86783. }
  86784. else {
  86785. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86786. }
  86787. impostor.setDeltaPosition(this._tmpPositionVector);
  86788. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86789. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86790. };
  86791. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86792. //impostor.physicsBody.dispose();
  86793. //Same as : (older oimo versions)
  86794. this.world.removeRigidBody(impostor.physicsBody);
  86795. };
  86796. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86797. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86798. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86799. if (!mainBody || !connectedBody) {
  86800. return;
  86801. }
  86802. var jointData = impostorJoint.joint.jointData;
  86803. var options = jointData.nativeParams || {};
  86804. var type;
  86805. var nativeJointData = {
  86806. body1: mainBody,
  86807. body2: connectedBody,
  86808. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86809. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86810. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86811. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86812. min: options.min,
  86813. max: options.max,
  86814. collision: options.collision || jointData.collision,
  86815. spring: options.spring,
  86816. //supporting older version of Oimo
  86817. world: this.world
  86818. };
  86819. switch (impostorJoint.joint.type) {
  86820. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86821. type = "jointBall";
  86822. break;
  86823. case BABYLON.PhysicsJoint.SpringJoint:
  86824. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86825. var springData = jointData;
  86826. nativeJointData.min = springData.length || nativeJointData.min;
  86827. //Max should also be set, just make sure it is at least min
  86828. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86829. case BABYLON.PhysicsJoint.DistanceJoint:
  86830. type = "jointDistance";
  86831. nativeJointData.max = jointData.maxDistance;
  86832. break;
  86833. case BABYLON.PhysicsJoint.PrismaticJoint:
  86834. type = "jointPrisme";
  86835. break;
  86836. case BABYLON.PhysicsJoint.SliderJoint:
  86837. type = "jointSlide";
  86838. break;
  86839. case BABYLON.PhysicsJoint.WheelJoint:
  86840. type = "jointWheel";
  86841. break;
  86842. case BABYLON.PhysicsJoint.HingeJoint:
  86843. default:
  86844. type = "jointHinge";
  86845. break;
  86846. }
  86847. nativeJointData.type = type;
  86848. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86849. };
  86850. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86851. //Bug in Oimo prevents us from disposing a joint in the playground
  86852. //joint.joint.physicsJoint.dispose();
  86853. //So we will bruteforce it!
  86854. try {
  86855. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86856. }
  86857. catch (e) {
  86858. BABYLON.Tools.Warn(e);
  86859. }
  86860. };
  86861. OimoJSPlugin.prototype.isSupported = function () {
  86862. return this.BJSOIMO !== undefined;
  86863. };
  86864. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86865. if (!impostor.physicsBody.sleeping) {
  86866. //TODO check that
  86867. /*if (impostor.physicsBody.shapes.next) {
  86868. var parentShape = this._getLastShape(impostor.physicsBody);
  86869. impostor.object.position.copyFrom(parentShape.position);
  86870. console.log(parentShape.position);
  86871. } else {*/
  86872. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86873. //}
  86874. if (impostor.object.rotationQuaternion) {
  86875. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86876. }
  86877. }
  86878. };
  86879. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86880. var body = impostor.physicsBody;
  86881. body.position.copy(newPosition);
  86882. body.orientation.copy(newRotation);
  86883. body.syncShapes();
  86884. body.awake();
  86885. };
  86886. /*private _getLastShape(body: any): any {
  86887. var lastShape = body.shapes;
  86888. while (lastShape.next) {
  86889. lastShape = lastShape.next;
  86890. }
  86891. return lastShape;
  86892. }*/
  86893. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86894. impostor.physicsBody.linearVelocity.copy(velocity);
  86895. };
  86896. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86897. impostor.physicsBody.angularVelocity.copy(velocity);
  86898. };
  86899. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86900. var v = impostor.physicsBody.linearVelocity;
  86901. if (!v) {
  86902. return null;
  86903. }
  86904. return new BABYLON.Vector3(v.x, v.y, v.z);
  86905. };
  86906. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86907. var v = impostor.physicsBody.angularVelocity;
  86908. if (!v) {
  86909. return null;
  86910. }
  86911. return new BABYLON.Vector3(v.x, v.y, v.z);
  86912. };
  86913. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86914. var staticBody = mass === 0;
  86915. //this will actually set the body's density and not its mass.
  86916. //But this is how oimo treats the mass variable.
  86917. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86918. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86919. };
  86920. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86921. return impostor.physicsBody.shapes.density;
  86922. };
  86923. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86924. return impostor.physicsBody.shapes.friction;
  86925. };
  86926. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86927. impostor.physicsBody.shapes.friction = friction;
  86928. };
  86929. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86930. return impostor.physicsBody.shapes.restitution;
  86931. };
  86932. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86933. impostor.physicsBody.shapes.restitution = restitution;
  86934. };
  86935. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86936. impostor.physicsBody.sleep();
  86937. };
  86938. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86939. impostor.physicsBody.awake();
  86940. };
  86941. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86942. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86943. if (minDistance !== void 0) {
  86944. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86945. }
  86946. };
  86947. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86948. //TODO separate rotational and transational motors.
  86949. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86950. if (motor) {
  86951. motor.setMotor(speed, maxForce);
  86952. }
  86953. };
  86954. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86955. //TODO separate rotational and transational motors.
  86956. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86957. if (motor) {
  86958. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86959. }
  86960. };
  86961. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86962. var body = impostor.physicsBody;
  86963. mesh.position.x = body.position.x;
  86964. mesh.position.y = body.position.y;
  86965. mesh.position.z = body.position.z;
  86966. if (mesh.rotationQuaternion) {
  86967. mesh.rotationQuaternion.x = body.orientation.x;
  86968. mesh.rotationQuaternion.y = body.orientation.y;
  86969. mesh.rotationQuaternion.z = body.orientation.z;
  86970. mesh.rotationQuaternion.w = body.orientation.s;
  86971. }
  86972. };
  86973. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86974. return impostor.physicsBody.shapes.radius;
  86975. };
  86976. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86977. var shape = impostor.physicsBody.shapes;
  86978. result.x = shape.halfWidth * 2;
  86979. result.y = shape.halfHeight * 2;
  86980. result.z = shape.halfDepth * 2;
  86981. };
  86982. OimoJSPlugin.prototype.dispose = function () {
  86983. this.world.clear();
  86984. };
  86985. return OimoJSPlugin;
  86986. }());
  86987. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86988. })(BABYLON || (BABYLON = {}));
  86989. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86990. var BABYLON;
  86991. (function (BABYLON) {
  86992. /*
  86993. * Based on jsTGALoader - Javascript loader for TGA file
  86994. * By Vincent Thibault
  86995. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86996. */
  86997. var TGATools = /** @class */ (function () {
  86998. function TGATools() {
  86999. }
  87000. TGATools.GetTGAHeader = function (data) {
  87001. var offset = 0;
  87002. var header = {
  87003. id_length: data[offset++],
  87004. colormap_type: data[offset++],
  87005. image_type: data[offset++],
  87006. colormap_index: data[offset++] | data[offset++] << 8,
  87007. colormap_length: data[offset++] | data[offset++] << 8,
  87008. colormap_size: data[offset++],
  87009. origin: [
  87010. data[offset++] | data[offset++] << 8,
  87011. data[offset++] | data[offset++] << 8
  87012. ],
  87013. width: data[offset++] | data[offset++] << 8,
  87014. height: data[offset++] | data[offset++] << 8,
  87015. pixel_size: data[offset++],
  87016. flags: data[offset++]
  87017. };
  87018. return header;
  87019. };
  87020. TGATools.UploadContent = function (gl, data) {
  87021. // Not enough data to contain header ?
  87022. if (data.length < 19) {
  87023. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  87024. return;
  87025. }
  87026. // Read Header
  87027. var offset = 18;
  87028. var header = TGATools.GetTGAHeader(data);
  87029. // Assume it's a valid Targa file.
  87030. if (header.id_length + offset > data.length) {
  87031. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  87032. return;
  87033. }
  87034. // Skip not needed data
  87035. offset += header.id_length;
  87036. var use_rle = false;
  87037. var use_pal = false;
  87038. var use_grey = false;
  87039. // Get some informations.
  87040. switch (header.image_type) {
  87041. case TGATools._TYPE_RLE_INDEXED:
  87042. use_rle = true;
  87043. case TGATools._TYPE_INDEXED:
  87044. use_pal = true;
  87045. break;
  87046. case TGATools._TYPE_RLE_RGB:
  87047. use_rle = true;
  87048. case TGATools._TYPE_RGB:
  87049. // use_rgb = true;
  87050. break;
  87051. case TGATools._TYPE_RLE_GREY:
  87052. use_rle = true;
  87053. case TGATools._TYPE_GREY:
  87054. use_grey = true;
  87055. break;
  87056. }
  87057. var pixel_data;
  87058. // var numAlphaBits = header.flags & 0xf;
  87059. var pixel_size = header.pixel_size >> 3;
  87060. var pixel_total = header.width * header.height * pixel_size;
  87061. // Read palettes
  87062. var palettes;
  87063. if (use_pal) {
  87064. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  87065. }
  87066. // Read LRE
  87067. if (use_rle) {
  87068. pixel_data = new Uint8Array(pixel_total);
  87069. var c, count, i;
  87070. var localOffset = 0;
  87071. var pixels = new Uint8Array(pixel_size);
  87072. while (offset < pixel_total && localOffset < pixel_total) {
  87073. c = data[offset++];
  87074. count = (c & 0x7f) + 1;
  87075. // RLE pixels
  87076. if (c & 0x80) {
  87077. // Bind pixel tmp array
  87078. for (i = 0; i < pixel_size; ++i) {
  87079. pixels[i] = data[offset++];
  87080. }
  87081. // Copy pixel array
  87082. for (i = 0; i < count; ++i) {
  87083. pixel_data.set(pixels, localOffset + i * pixel_size);
  87084. }
  87085. localOffset += pixel_size * count;
  87086. }
  87087. // Raw pixels
  87088. else {
  87089. count *= pixel_size;
  87090. for (i = 0; i < count; ++i) {
  87091. pixel_data[localOffset + i] = data[offset++];
  87092. }
  87093. localOffset += count;
  87094. }
  87095. }
  87096. }
  87097. // RAW Pixels
  87098. else {
  87099. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  87100. }
  87101. // Load to texture
  87102. var x_start, y_start, x_step, y_step, y_end, x_end;
  87103. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  87104. default:
  87105. case TGATools._ORIGIN_UL:
  87106. x_start = 0;
  87107. x_step = 1;
  87108. x_end = header.width;
  87109. y_start = 0;
  87110. y_step = 1;
  87111. y_end = header.height;
  87112. break;
  87113. case TGATools._ORIGIN_BL:
  87114. x_start = 0;
  87115. x_step = 1;
  87116. x_end = header.width;
  87117. y_start = header.height - 1;
  87118. y_step = -1;
  87119. y_end = -1;
  87120. break;
  87121. case TGATools._ORIGIN_UR:
  87122. x_start = header.width - 1;
  87123. x_step = -1;
  87124. x_end = -1;
  87125. y_start = 0;
  87126. y_step = 1;
  87127. y_end = header.height;
  87128. break;
  87129. case TGATools._ORIGIN_BR:
  87130. x_start = header.width - 1;
  87131. x_step = -1;
  87132. x_end = -1;
  87133. y_start = header.height - 1;
  87134. y_step = -1;
  87135. y_end = -1;
  87136. break;
  87137. }
  87138. // Load the specify method
  87139. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  87140. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  87141. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  87142. };
  87143. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87144. var image = pixel_data, colormap = palettes;
  87145. var width = header.width, height = header.height;
  87146. var color, i = 0, x, y;
  87147. var imageData = new Uint8Array(width * height * 4);
  87148. for (y = y_start; y !== y_end; y += y_step) {
  87149. for (x = x_start; x !== x_end; x += x_step, i++) {
  87150. color = image[i];
  87151. imageData[(x + width * y) * 4 + 3] = 255;
  87152. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  87153. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  87154. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  87155. }
  87156. }
  87157. return imageData;
  87158. };
  87159. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87160. var image = pixel_data;
  87161. var width = header.width, height = header.height;
  87162. var color, i = 0, x, y;
  87163. var imageData = new Uint8Array(width * height * 4);
  87164. for (y = y_start; y !== y_end; y += y_step) {
  87165. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87166. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  87167. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  87168. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  87169. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  87170. imageData[(x + width * y) * 4 + 0] = r;
  87171. imageData[(x + width * y) * 4 + 1] = g;
  87172. imageData[(x + width * y) * 4 + 2] = b;
  87173. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  87174. }
  87175. }
  87176. return imageData;
  87177. };
  87178. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87179. var image = pixel_data;
  87180. var width = header.width, height = header.height;
  87181. var i = 0, x, y;
  87182. var imageData = new Uint8Array(width * height * 4);
  87183. for (y = y_start; y !== y_end; y += y_step) {
  87184. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  87185. imageData[(x + width * y) * 4 + 3] = 255;
  87186. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87187. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87188. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87189. }
  87190. }
  87191. return imageData;
  87192. };
  87193. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87194. var image = pixel_data;
  87195. var width = header.width, height = header.height;
  87196. var i = 0, x, y;
  87197. var imageData = new Uint8Array(width * height * 4);
  87198. for (y = y_start; y !== y_end; y += y_step) {
  87199. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  87200. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87201. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  87202. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  87203. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  87204. }
  87205. }
  87206. return imageData;
  87207. };
  87208. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87209. var image = pixel_data;
  87210. var width = header.width, height = header.height;
  87211. var color, i = 0, x, y;
  87212. var imageData = new Uint8Array(width * height * 4);
  87213. for (y = y_start; y !== y_end; y += y_step) {
  87214. for (x = x_start; x !== x_end; x += x_step, i++) {
  87215. color = image[i];
  87216. imageData[(x + width * y) * 4 + 0] = color;
  87217. imageData[(x + width * y) * 4 + 1] = color;
  87218. imageData[(x + width * y) * 4 + 2] = color;
  87219. imageData[(x + width * y) * 4 + 3] = 255;
  87220. }
  87221. }
  87222. return imageData;
  87223. };
  87224. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  87225. var image = pixel_data;
  87226. var width = header.width, height = header.height;
  87227. var i = 0, x, y;
  87228. var imageData = new Uint8Array(width * height * 4);
  87229. for (y = y_start; y !== y_end; y += y_step) {
  87230. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  87231. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  87232. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  87233. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  87234. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  87235. }
  87236. }
  87237. return imageData;
  87238. };
  87239. //private static _TYPE_NO_DATA = 0;
  87240. TGATools._TYPE_INDEXED = 1;
  87241. TGATools._TYPE_RGB = 2;
  87242. TGATools._TYPE_GREY = 3;
  87243. TGATools._TYPE_RLE_INDEXED = 9;
  87244. TGATools._TYPE_RLE_RGB = 10;
  87245. TGATools._TYPE_RLE_GREY = 11;
  87246. TGATools._ORIGIN_MASK = 0x30;
  87247. TGATools._ORIGIN_SHIFT = 0x04;
  87248. TGATools._ORIGIN_BL = 0x00;
  87249. TGATools._ORIGIN_BR = 0x01;
  87250. TGATools._ORIGIN_UL = 0x02;
  87251. TGATools._ORIGIN_UR = 0x03;
  87252. return TGATools;
  87253. }());
  87254. BABYLON.TGATools = TGATools;
  87255. })(BABYLON || (BABYLON = {}));
  87256. //# sourceMappingURL=babylon.tga.js.map
  87257. var BABYLON;
  87258. (function (BABYLON) {
  87259. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  87260. // All values and structures referenced from:
  87261. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  87262. var DDS_MAGIC = 0x20534444;
  87263. var
  87264. //DDSD_CAPS = 0x1,
  87265. //DDSD_HEIGHT = 0x2,
  87266. //DDSD_WIDTH = 0x4,
  87267. //DDSD_PITCH = 0x8,
  87268. //DDSD_PIXELFORMAT = 0x1000,
  87269. DDSD_MIPMAPCOUNT = 0x20000;
  87270. //DDSD_LINEARSIZE = 0x80000,
  87271. //DDSD_DEPTH = 0x800000;
  87272. // var DDSCAPS_COMPLEX = 0x8,
  87273. // DDSCAPS_MIPMAP = 0x400000,
  87274. // DDSCAPS_TEXTURE = 0x1000;
  87275. var DDSCAPS2_CUBEMAP = 0x200;
  87276. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  87277. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  87278. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  87279. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  87280. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  87281. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  87282. // DDSCAPS2_VOLUME = 0x200000;
  87283. var
  87284. //DDPF_ALPHAPIXELS = 0x1,
  87285. //DDPF_ALPHA = 0x2,
  87286. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  87287. //DDPF_YUV = 0x200,
  87288. DDPF_LUMINANCE = 0x20000;
  87289. function FourCCToInt32(value) {
  87290. return value.charCodeAt(0) +
  87291. (value.charCodeAt(1) << 8) +
  87292. (value.charCodeAt(2) << 16) +
  87293. (value.charCodeAt(3) << 24);
  87294. }
  87295. function Int32ToFourCC(value) {
  87296. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87297. }
  87298. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87299. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87300. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87301. var FOURCC_DX10 = FourCCToInt32("DX10");
  87302. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87303. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87304. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87305. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87306. var headerLengthInt = 31; // The header length in 32 bit ints
  87307. // Offsets into the header array
  87308. var off_magic = 0;
  87309. var off_size = 1;
  87310. var off_flags = 2;
  87311. var off_height = 3;
  87312. var off_width = 4;
  87313. var off_mipmapCount = 7;
  87314. var off_pfFlags = 20;
  87315. var off_pfFourCC = 21;
  87316. var off_RGBbpp = 22;
  87317. var off_RMask = 23;
  87318. var off_GMask = 24;
  87319. var off_BMask = 25;
  87320. var off_AMask = 26;
  87321. // var off_caps1 = 27;
  87322. var off_caps2 = 28;
  87323. // var off_caps3 = 29;
  87324. // var off_caps4 = 30;
  87325. var off_dxgiFormat = 32;
  87326. ;
  87327. var DDSTools = /** @class */ (function () {
  87328. function DDSTools() {
  87329. }
  87330. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87331. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87332. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87333. var mipmapCount = 1;
  87334. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87335. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87336. }
  87337. var fourCC = header[off_pfFourCC];
  87338. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87339. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87340. switch (fourCC) {
  87341. case FOURCC_D3DFMT_R16G16B16A16F:
  87342. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87343. break;
  87344. case FOURCC_D3DFMT_R32G32B32A32F:
  87345. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87346. break;
  87347. case FOURCC_DX10:
  87348. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87349. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87350. break;
  87351. }
  87352. }
  87353. return {
  87354. width: header[off_width],
  87355. height: header[off_height],
  87356. mipmapCount: mipmapCount,
  87357. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87358. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87359. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87360. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87361. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87362. dxgiFormat: dxgiFormat,
  87363. textureType: textureType
  87364. };
  87365. };
  87366. DDSTools._ToHalfFloat = function (value) {
  87367. if (!DDSTools._FloatView) {
  87368. DDSTools._FloatView = new Float32Array(1);
  87369. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87370. }
  87371. DDSTools._FloatView[0] = value;
  87372. var x = DDSTools._Int32View[0];
  87373. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87374. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87375. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87376. /* If zero, or denormal, or exponent underflows too much for a denormal
  87377. * half, return signed zero. */
  87378. if (e < 103) {
  87379. return bits;
  87380. }
  87381. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87382. if (e > 142) {
  87383. bits |= 0x7c00;
  87384. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87385. * not Inf, so make sure we set one mantissa bit too. */
  87386. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87387. return bits;
  87388. }
  87389. /* If exponent underflows but not too much, return a denormal */
  87390. if (e < 113) {
  87391. m |= 0x0800;
  87392. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87393. * to 1, which is OK. */
  87394. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87395. return bits;
  87396. }
  87397. bits |= ((e - 112) << 10) | (m >> 1);
  87398. bits += m & 1;
  87399. return bits;
  87400. };
  87401. DDSTools._FromHalfFloat = function (value) {
  87402. var s = (value & 0x8000) >> 15;
  87403. var e = (value & 0x7C00) >> 10;
  87404. var f = value & 0x03FF;
  87405. if (e === 0) {
  87406. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87407. }
  87408. else if (e == 0x1F) {
  87409. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87410. }
  87411. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87412. };
  87413. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87414. var destArray = new Float32Array(dataLength);
  87415. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87416. var index = 0;
  87417. for (var y = 0; y < height; y++) {
  87418. for (var x = 0; x < width; x++) {
  87419. var srcPos = (x + y * width) * 4;
  87420. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87421. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87422. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87423. if (DDSTools.StoreLODInAlphaChannel) {
  87424. destArray[index + 3] = lod;
  87425. }
  87426. else {
  87427. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87428. }
  87429. index += 4;
  87430. }
  87431. }
  87432. return destArray;
  87433. };
  87434. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87435. if (DDSTools.StoreLODInAlphaChannel) {
  87436. var destArray = new Uint16Array(dataLength);
  87437. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87438. var index = 0;
  87439. for (var y = 0; y < height; y++) {
  87440. for (var x = 0; x < width; x++) {
  87441. var srcPos = (x + y * width) * 4;
  87442. destArray[index] = srcData[srcPos];
  87443. destArray[index + 1] = srcData[srcPos + 1];
  87444. destArray[index + 2] = srcData[srcPos + 2];
  87445. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87446. index += 4;
  87447. }
  87448. }
  87449. return destArray;
  87450. }
  87451. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87452. };
  87453. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87454. if (DDSTools.StoreLODInAlphaChannel) {
  87455. var destArray = new Float32Array(dataLength);
  87456. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87457. var index = 0;
  87458. for (var y = 0; y < height; y++) {
  87459. for (var x = 0; x < width; x++) {
  87460. var srcPos = (x + y * width) * 4;
  87461. destArray[index] = srcData[srcPos];
  87462. destArray[index + 1] = srcData[srcPos + 1];
  87463. destArray[index + 2] = srcData[srcPos + 2];
  87464. destArray[index + 3] = lod;
  87465. index += 4;
  87466. }
  87467. }
  87468. return destArray;
  87469. }
  87470. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87471. };
  87472. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87473. var destArray = new Uint8Array(dataLength);
  87474. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87475. var index = 0;
  87476. for (var y = 0; y < height; y++) {
  87477. for (var x = 0; x < width; x++) {
  87478. var srcPos = (x + y * width) * 4;
  87479. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87480. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87481. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87482. if (DDSTools.StoreLODInAlphaChannel) {
  87483. destArray[index + 3] = lod;
  87484. }
  87485. else {
  87486. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87487. }
  87488. index += 4;
  87489. }
  87490. }
  87491. return destArray;
  87492. };
  87493. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87494. var destArray = new Uint8Array(dataLength);
  87495. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87496. var index = 0;
  87497. for (var y = 0; y < height; y++) {
  87498. for (var x = 0; x < width; x++) {
  87499. var srcPos = (x + y * width) * 4;
  87500. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87501. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87502. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87503. if (DDSTools.StoreLODInAlphaChannel) {
  87504. destArray[index + 3] = lod;
  87505. }
  87506. else {
  87507. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87508. }
  87509. index += 4;
  87510. }
  87511. }
  87512. return destArray;
  87513. };
  87514. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87515. var byteArray = new Uint8Array(dataLength);
  87516. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87517. var index = 0;
  87518. for (var y = 0; y < height; y++) {
  87519. for (var x = 0; x < width; x++) {
  87520. var srcPos = (x + y * width) * 4;
  87521. byteArray[index] = srcData[srcPos + rOffset];
  87522. byteArray[index + 1] = srcData[srcPos + gOffset];
  87523. byteArray[index + 2] = srcData[srcPos + bOffset];
  87524. byteArray[index + 3] = srcData[srcPos + aOffset];
  87525. index += 4;
  87526. }
  87527. }
  87528. return byteArray;
  87529. };
  87530. DDSTools._ExtractLongWordOrder = function (value) {
  87531. if (value === 0 || value === 255 || value === -16777216) {
  87532. return 0;
  87533. }
  87534. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87535. };
  87536. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87537. var byteArray = new Uint8Array(dataLength);
  87538. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87539. var index = 0;
  87540. for (var y = 0; y < height; y++) {
  87541. for (var x = 0; x < width; x++) {
  87542. var srcPos = (x + y * width) * 3;
  87543. byteArray[index] = srcData[srcPos + rOffset];
  87544. byteArray[index + 1] = srcData[srcPos + gOffset];
  87545. byteArray[index + 2] = srcData[srcPos + bOffset];
  87546. index += 3;
  87547. }
  87548. }
  87549. return byteArray;
  87550. };
  87551. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87552. var byteArray = new Uint8Array(dataLength);
  87553. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87554. var index = 0;
  87555. for (var y = 0; y < height; y++) {
  87556. for (var x = 0; x < width; x++) {
  87557. var srcPos = (x + y * width);
  87558. byteArray[index] = srcData[srcPos];
  87559. index++;
  87560. }
  87561. }
  87562. return byteArray;
  87563. };
  87564. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87565. if (lodIndex === void 0) { lodIndex = -1; }
  87566. var sphericalPolynomialFaces = null;
  87567. if (info.sphericalPolynomial) {
  87568. sphericalPolynomialFaces = new Array();
  87569. }
  87570. var ext = engine.getCaps().s3tc;
  87571. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87572. var fourCC, width, height, dataLength = 0, dataOffset;
  87573. var byteArray, mipmapCount, mip;
  87574. var internalFormat = 0;
  87575. var format = 0;
  87576. var blockBytes = 1;
  87577. if (header[off_magic] !== DDS_MAGIC) {
  87578. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87579. return;
  87580. }
  87581. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87582. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87583. return;
  87584. }
  87585. if (info.isCompressed && !ext) {
  87586. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87587. return;
  87588. }
  87589. var bpp = header[off_RGBbpp];
  87590. dataOffset = header[off_size] + 4;
  87591. var computeFormats = false;
  87592. if (info.isFourCC) {
  87593. fourCC = header[off_pfFourCC];
  87594. switch (fourCC) {
  87595. case FOURCC_DXT1:
  87596. blockBytes = 8;
  87597. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87598. break;
  87599. case FOURCC_DXT3:
  87600. blockBytes = 16;
  87601. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87602. break;
  87603. case FOURCC_DXT5:
  87604. blockBytes = 16;
  87605. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87606. break;
  87607. case FOURCC_D3DFMT_R16G16B16A16F:
  87608. computeFormats = true;
  87609. break;
  87610. case FOURCC_D3DFMT_R32G32B32A32F:
  87611. computeFormats = true;
  87612. break;
  87613. case FOURCC_DX10:
  87614. // There is an additionnal header so dataOffset need to be changed
  87615. dataOffset += 5 * 4; // 5 uints
  87616. var supported = false;
  87617. switch (info.dxgiFormat) {
  87618. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87619. computeFormats = true;
  87620. supported = true;
  87621. break;
  87622. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87623. info.isRGB = true;
  87624. info.isFourCC = false;
  87625. bpp = 32;
  87626. supported = true;
  87627. break;
  87628. }
  87629. if (supported) {
  87630. break;
  87631. }
  87632. default:
  87633. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87634. return;
  87635. }
  87636. }
  87637. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87638. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87639. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87640. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87641. if (computeFormats) {
  87642. format = engine._getWebGLTextureType(info.textureType);
  87643. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87644. }
  87645. mipmapCount = 1;
  87646. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87647. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87648. }
  87649. for (var face = 0; face < faces; face++) {
  87650. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87651. width = header[off_width];
  87652. height = header[off_height];
  87653. for (mip = 0; mip < mipmapCount; ++mip) {
  87654. if (lodIndex === -1 || lodIndex === mip) {
  87655. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87656. var i = (lodIndex === -1) ? mip : 0;
  87657. if (!info.isCompressed && info.isFourCC) {
  87658. dataLength = width * height * 4;
  87659. var floatArray = null;
  87660. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87661. if (bpp === 128) {
  87662. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87663. if (sphericalPolynomialFaces && i == 0) {
  87664. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87665. }
  87666. }
  87667. else if (bpp === 64) {
  87668. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87669. if (sphericalPolynomialFaces && i == 0) {
  87670. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87671. }
  87672. }
  87673. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87674. format = engine._getWebGLTextureType(info.textureType);
  87675. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87676. }
  87677. else {
  87678. if (bpp === 128) {
  87679. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87680. if (sphericalPolynomialFaces && i == 0) {
  87681. sphericalPolynomialFaces.push(floatArray);
  87682. }
  87683. }
  87684. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87685. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87686. if (sphericalPolynomialFaces && i == 0) {
  87687. sphericalPolynomialFaces.push(floatArray);
  87688. }
  87689. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87690. format = engine._getWebGLTextureType(info.textureType);
  87691. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87692. }
  87693. else { // 64
  87694. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87695. if (sphericalPolynomialFaces && i == 0) {
  87696. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87697. }
  87698. }
  87699. }
  87700. if (floatArray) {
  87701. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87702. }
  87703. }
  87704. else if (info.isRGB) {
  87705. if (bpp === 24) {
  87706. dataLength = width * height * 3;
  87707. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87708. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87709. }
  87710. else { // 32
  87711. dataLength = width * height * 4;
  87712. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87713. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87714. }
  87715. }
  87716. else if (info.isLuminance) {
  87717. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87718. var unpaddedRowSize = width;
  87719. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87720. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87721. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87722. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87723. }
  87724. else {
  87725. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87726. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87727. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87728. }
  87729. }
  87730. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87731. width *= 0.5;
  87732. height *= 0.5;
  87733. width = Math.max(1.0, width);
  87734. height = Math.max(1.0, height);
  87735. }
  87736. if (currentFace !== undefined) {
  87737. // Loading a single face
  87738. break;
  87739. }
  87740. }
  87741. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87742. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87743. size: header[off_width],
  87744. right: sphericalPolynomialFaces[0],
  87745. left: sphericalPolynomialFaces[1],
  87746. up: sphericalPolynomialFaces[2],
  87747. down: sphericalPolynomialFaces[3],
  87748. front: sphericalPolynomialFaces[4],
  87749. back: sphericalPolynomialFaces[5],
  87750. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87751. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87752. gammaSpace: false,
  87753. });
  87754. }
  87755. else {
  87756. info.sphericalPolynomial = undefined;
  87757. }
  87758. };
  87759. DDSTools.StoreLODInAlphaChannel = false;
  87760. return DDSTools;
  87761. }());
  87762. BABYLON.DDSTools = DDSTools;
  87763. })(BABYLON || (BABYLON = {}));
  87764. //# sourceMappingURL=babylon.dds.js.map
  87765. var BABYLON;
  87766. (function (BABYLON) {
  87767. /**
  87768. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87769. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87770. */
  87771. var KhronosTextureContainer = /** @class */ (function () {
  87772. /**
  87773. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87774. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87775. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87776. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87777. */
  87778. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87779. this.arrayBuffer = arrayBuffer;
  87780. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87781. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87782. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87783. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87784. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87785. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87786. BABYLON.Tools.Error("texture missing KTX identifier");
  87787. return;
  87788. }
  87789. // load the reset of the header in native 32 bit int
  87790. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87791. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87792. var oppositeEndianess = header[0] === 0x01020304;
  87793. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87794. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87795. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87796. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87797. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87798. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87799. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87800. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87801. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87802. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87803. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87804. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87805. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87806. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87807. if (this.glType !== 0) {
  87808. BABYLON.Tools.Error("only compressed formats currently supported");
  87809. return;
  87810. }
  87811. else {
  87812. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87813. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87814. }
  87815. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87816. BABYLON.Tools.Error("only 2D textures currently supported");
  87817. return;
  87818. }
  87819. if (this.numberOfArrayElements !== 0) {
  87820. BABYLON.Tools.Error("texture arrays not currently supported");
  87821. return;
  87822. }
  87823. if (this.numberOfFaces !== facesExpected) {
  87824. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87825. return;
  87826. }
  87827. // we now have a completely validated file, so could use existence of loadType as success
  87828. // would need to make this more elaborate & adjust checks above to support more than one load type
  87829. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87830. }
  87831. // not as fast hardware based, but will probably never need to use
  87832. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87833. return ((val & 0xFF) << 24)
  87834. | ((val & 0xFF00) << 8)
  87835. | ((val >> 8) & 0xFF00)
  87836. | ((val >> 24) & 0xFF);
  87837. };
  87838. /**
  87839. * It is assumed that the texture has already been created & is currently bound
  87840. */
  87841. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87842. switch (this.loadType) {
  87843. case KhronosTextureContainer.COMPRESSED_2D:
  87844. this._upload2DCompressedLevels(gl, loadMipmaps);
  87845. break;
  87846. case KhronosTextureContainer.TEX_2D:
  87847. case KhronosTextureContainer.COMPRESSED_3D:
  87848. case KhronosTextureContainer.TEX_3D:
  87849. }
  87850. };
  87851. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87852. // initialize width & height for level 1
  87853. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87854. var width = this.pixelWidth;
  87855. var height = this.pixelHeight;
  87856. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87857. for (var level = 0; level < mipmapCount; level++) {
  87858. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87859. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87860. for (var face = 0; face < this.numberOfFaces; face++) {
  87861. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87862. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87863. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87864. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87865. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87866. }
  87867. width = Math.max(1.0, width * 0.5);
  87868. height = Math.max(1.0, height * 0.5);
  87869. }
  87870. };
  87871. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87872. // load types
  87873. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87874. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87875. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87876. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87877. return KhronosTextureContainer;
  87878. }());
  87879. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87880. })(BABYLON || (BABYLON = {}));
  87881. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87882. var BABYLON;
  87883. (function (BABYLON) {
  87884. var Debug;
  87885. (function (Debug) {
  87886. /**
  87887. * Class used to render a debug view of a given skeleton
  87888. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87889. */
  87890. var SkeletonViewer = /** @class */ (function () {
  87891. /**
  87892. * Creates a new SkeletonViewer
  87893. * @param skeleton defines the skeleton to render
  87894. * @param mesh defines the mesh attached to the skeleton
  87895. * @param scene defines the hosting scene
  87896. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87897. * @param renderingGroupId defines the rendering group id to use with the viewer
  87898. */
  87899. function SkeletonViewer(
  87900. /** defines the skeleton to render */
  87901. skeleton,
  87902. /** defines the mesh attached to the skeleton */
  87903. mesh, scene,
  87904. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87905. autoUpdateBonesMatrices,
  87906. /** defines the rendering group id to use with the viewer */
  87907. renderingGroupId) {
  87908. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87909. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87910. this.skeleton = skeleton;
  87911. this.mesh = mesh;
  87912. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87913. this.renderingGroupId = renderingGroupId;
  87914. /** Gets or sets the color used to render the skeleton */
  87915. this.color = BABYLON.Color3.White();
  87916. this._debugLines = new Array();
  87917. this._isEnabled = false;
  87918. this._scene = scene;
  87919. this.update();
  87920. this._renderFunction = this.update.bind(this);
  87921. }
  87922. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87923. get: function () {
  87924. return this._isEnabled;
  87925. },
  87926. /** Gets or sets a boolean indicating if the viewer is enabled */
  87927. set: function (value) {
  87928. if (this._isEnabled === value) {
  87929. return;
  87930. }
  87931. this._isEnabled = value;
  87932. if (value) {
  87933. this._scene.registerBeforeRender(this._renderFunction);
  87934. }
  87935. else {
  87936. this._scene.unregisterBeforeRender(this._renderFunction);
  87937. }
  87938. },
  87939. enumerable: true,
  87940. configurable: true
  87941. });
  87942. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87943. if (x === void 0) { x = 0; }
  87944. if (y === void 0) { y = 0; }
  87945. if (z === void 0) { z = 0; }
  87946. var tmat = BABYLON.Tmp.Matrix[0];
  87947. var parentBone = bone.getParent();
  87948. tmat.copyFrom(bone.getLocalMatrix());
  87949. if (x !== 0 || y !== 0 || z !== 0) {
  87950. var tmat2 = BABYLON.Tmp.Matrix[1];
  87951. BABYLON.Matrix.IdentityToRef(tmat2);
  87952. tmat2.m[12] = x;
  87953. tmat2.m[13] = y;
  87954. tmat2.m[14] = z;
  87955. tmat2.multiplyToRef(tmat, tmat);
  87956. }
  87957. if (parentBone) {
  87958. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87959. }
  87960. tmat.multiplyToRef(meshMat, tmat);
  87961. position.x = tmat.m[12];
  87962. position.y = tmat.m[13];
  87963. position.z = tmat.m[14];
  87964. };
  87965. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87966. var len = bones.length;
  87967. var meshPos = this.mesh.position;
  87968. for (var i = 0; i < len; i++) {
  87969. var bone = bones[i];
  87970. var points = this._debugLines[i];
  87971. if (!points) {
  87972. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87973. this._debugLines[i] = points;
  87974. }
  87975. this._getBonePosition(points[0], bone, meshMat);
  87976. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87977. points[0].subtractInPlace(meshPos);
  87978. points[1].subtractInPlace(meshPos);
  87979. }
  87980. };
  87981. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87982. var len = bones.length;
  87983. var boneNum = 0;
  87984. var meshPos = this.mesh.position;
  87985. for (var i = len - 1; i >= 0; i--) {
  87986. var childBone = bones[i];
  87987. var parentBone = childBone.getParent();
  87988. if (!parentBone) {
  87989. continue;
  87990. }
  87991. var points = this._debugLines[boneNum];
  87992. if (!points) {
  87993. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87994. this._debugLines[boneNum] = points;
  87995. }
  87996. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87997. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87998. points[0].subtractInPlace(meshPos);
  87999. points[1].subtractInPlace(meshPos);
  88000. boneNum++;
  88001. }
  88002. };
  88003. /** Update the viewer to sync with current skeleton state */
  88004. SkeletonViewer.prototype.update = function () {
  88005. if (this.autoUpdateBonesMatrices) {
  88006. this.skeleton.computeAbsoluteTransforms();
  88007. }
  88008. if (this.skeleton.bones[0].length === undefined) {
  88009. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88010. }
  88011. else {
  88012. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  88013. }
  88014. if (!this._debugMesh) {
  88015. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  88016. this._debugMesh.renderingGroupId = this.renderingGroupId;
  88017. }
  88018. else {
  88019. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  88020. }
  88021. this._debugMesh.position.copyFrom(this.mesh.position);
  88022. this._debugMesh.color = this.color;
  88023. };
  88024. /** Release associated resources */
  88025. SkeletonViewer.prototype.dispose = function () {
  88026. if (this._debugMesh) {
  88027. this.isEnabled = false;
  88028. this._debugMesh.dispose();
  88029. this._debugMesh = null;
  88030. }
  88031. };
  88032. return SkeletonViewer;
  88033. }());
  88034. Debug.SkeletonViewer = SkeletonViewer;
  88035. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88036. })(BABYLON || (BABYLON = {}));
  88037. //# sourceMappingURL=babylon.skeletonViewer.js.map
  88038. /**
  88039. * Module Debug contains the (visual) components to debug a scene correctly
  88040. */
  88041. var BABYLON;
  88042. (function (BABYLON) {
  88043. var Debug;
  88044. (function (Debug) {
  88045. /**
  88046. * The Axes viewer will show 3 axes in a specific point in space
  88047. */
  88048. var AxesViewer = /** @class */ (function () {
  88049. /**
  88050. * Creates a new AxesViewer
  88051. * @param scene defines the hosting scene
  88052. * @param scaleLines defines a number used to scale line length (1 by default)
  88053. */
  88054. function AxesViewer(scene, scaleLines) {
  88055. if (scaleLines === void 0) { scaleLines = 1; }
  88056. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88057. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88058. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  88059. /**
  88060. * Gets or sets a number used to scale line length
  88061. */
  88062. this.scaleLines = 1;
  88063. this.scaleLines = scaleLines;
  88064. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  88065. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  88066. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  88067. this._xmesh.renderingGroupId = 2;
  88068. this._ymesh.renderingGroupId = 2;
  88069. this._zmesh.renderingGroupId = 2;
  88070. this._xmesh.material.checkReadyOnlyOnce = true;
  88071. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  88072. this._ymesh.material.checkReadyOnlyOnce = true;
  88073. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  88074. this._zmesh.material.checkReadyOnlyOnce = true;
  88075. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  88076. this.scene = scene;
  88077. }
  88078. /**
  88079. * Force the viewer to update
  88080. * @param position defines the position of the viewer
  88081. * @param xaxis defines the x axis of the viewer
  88082. * @param yaxis defines the y axis of the viewer
  88083. * @param zaxis defines the z axis of the viewer
  88084. */
  88085. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  88086. var scaleLines = this.scaleLines;
  88087. if (this._xmesh) {
  88088. this._xmesh.position.copyFrom(position);
  88089. }
  88090. if (this._ymesh) {
  88091. this._ymesh.position.copyFrom(position);
  88092. }
  88093. if (this._zmesh) {
  88094. this._zmesh.position.copyFrom(position);
  88095. }
  88096. var point2 = this._xline[1];
  88097. point2.x = xaxis.x * scaleLines;
  88098. point2.y = xaxis.y * scaleLines;
  88099. point2.z = xaxis.z * scaleLines;
  88100. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  88101. point2 = this._yline[1];
  88102. point2.x = yaxis.x * scaleLines;
  88103. point2.y = yaxis.y * scaleLines;
  88104. point2.z = yaxis.z * scaleLines;
  88105. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  88106. point2 = this._zline[1];
  88107. point2.x = zaxis.x * scaleLines;
  88108. point2.y = zaxis.y * scaleLines;
  88109. point2.z = zaxis.z * scaleLines;
  88110. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  88111. };
  88112. /** Releases resources */
  88113. AxesViewer.prototype.dispose = function () {
  88114. if (this._xmesh) {
  88115. this._xmesh.dispose();
  88116. }
  88117. if (this._ymesh) {
  88118. this._ymesh.dispose();
  88119. }
  88120. if (this._zmesh) {
  88121. this._zmesh.dispose();
  88122. }
  88123. this._xmesh = null;
  88124. this._ymesh = null;
  88125. this._zmesh = null;
  88126. this.scene = null;
  88127. };
  88128. return AxesViewer;
  88129. }());
  88130. Debug.AxesViewer = AxesViewer;
  88131. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88132. })(BABYLON || (BABYLON = {}));
  88133. //# sourceMappingURL=babylon.axesViewer.js.map
  88134. var BABYLON;
  88135. (function (BABYLON) {
  88136. var Debug;
  88137. (function (Debug) {
  88138. /**
  88139. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  88140. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  88141. */
  88142. var BoneAxesViewer = /** @class */ (function (_super) {
  88143. __extends(BoneAxesViewer, _super);
  88144. /**
  88145. * Creates a new BoneAxesViewer
  88146. * @param scene defines the hosting scene
  88147. * @param bone defines the target bone
  88148. * @param mesh defines the target mesh
  88149. * @param scaleLines defines a scaling factor for line length (1 by default)
  88150. */
  88151. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  88152. if (scaleLines === void 0) { scaleLines = 1; }
  88153. var _this = _super.call(this, scene, scaleLines) || this;
  88154. /** Gets current position */
  88155. _this.pos = BABYLON.Vector3.Zero();
  88156. /** Gets direction of X axis */
  88157. _this.xaxis = BABYLON.Vector3.Zero();
  88158. /** Gets direction of Y axis */
  88159. _this.yaxis = BABYLON.Vector3.Zero();
  88160. /** Gets direction of Z axis */
  88161. _this.zaxis = BABYLON.Vector3.Zero();
  88162. _this.mesh = mesh;
  88163. _this.bone = bone;
  88164. return _this;
  88165. }
  88166. /**
  88167. * Force the viewer to update
  88168. */
  88169. BoneAxesViewer.prototype.update = function () {
  88170. if (!this.mesh || !this.bone) {
  88171. return;
  88172. }
  88173. var bone = this.bone;
  88174. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  88175. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  88176. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  88177. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  88178. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  88179. };
  88180. /** Releases resources */
  88181. BoneAxesViewer.prototype.dispose = function () {
  88182. if (this.mesh) {
  88183. this.mesh = null;
  88184. this.bone = null;
  88185. _super.prototype.dispose.call(this);
  88186. }
  88187. };
  88188. return BoneAxesViewer;
  88189. }(Debug.AxesViewer));
  88190. Debug.BoneAxesViewer = BoneAxesViewer;
  88191. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88192. })(BABYLON || (BABYLON = {}));
  88193. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  88194. var BABYLON;
  88195. (function (BABYLON) {
  88196. var RayHelper = /** @class */ (function () {
  88197. function RayHelper(ray) {
  88198. this.ray = ray;
  88199. }
  88200. RayHelper.CreateAndShow = function (ray, scene, color) {
  88201. var helper = new RayHelper(ray);
  88202. helper.show(scene, color);
  88203. return helper;
  88204. };
  88205. RayHelper.prototype.show = function (scene, color) {
  88206. if (!this._renderFunction && this.ray) {
  88207. var ray = this.ray;
  88208. this._renderFunction = this._render.bind(this);
  88209. this._scene = scene;
  88210. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  88211. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  88212. if (this._renderFunction) {
  88213. this._scene.registerBeforeRender(this._renderFunction);
  88214. }
  88215. }
  88216. if (color && this._renderLine) {
  88217. this._renderLine.color.copyFrom(color);
  88218. }
  88219. };
  88220. RayHelper.prototype.hide = function () {
  88221. if (this._renderFunction && this._scene) {
  88222. this._scene.unregisterBeforeRender(this._renderFunction);
  88223. this._scene = null;
  88224. this._renderFunction = null;
  88225. if (this._renderLine) {
  88226. this._renderLine.dispose();
  88227. this._renderLine = null;
  88228. }
  88229. this._renderPoints = [];
  88230. }
  88231. };
  88232. RayHelper.prototype._render = function () {
  88233. var ray = this.ray;
  88234. if (!ray) {
  88235. return;
  88236. }
  88237. var point = this._renderPoints[1];
  88238. var len = Math.min(ray.length, 1000000);
  88239. point.copyFrom(ray.direction);
  88240. point.scaleInPlace(len);
  88241. point.addInPlace(ray.origin);
  88242. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  88243. };
  88244. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  88245. this._attachedToMesh = mesh;
  88246. var ray = this.ray;
  88247. if (!ray) {
  88248. return;
  88249. }
  88250. if (!ray.direction) {
  88251. ray.direction = BABYLON.Vector3.Zero();
  88252. }
  88253. if (!ray.origin) {
  88254. ray.origin = BABYLON.Vector3.Zero();
  88255. }
  88256. if (length) {
  88257. ray.length = length;
  88258. }
  88259. if (!meshSpaceOrigin) {
  88260. meshSpaceOrigin = BABYLON.Vector3.Zero();
  88261. }
  88262. if (!meshSpaceDirection) {
  88263. // -1 so that this will work with Mesh.lookAt
  88264. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  88265. }
  88266. if (!this._meshSpaceDirection) {
  88267. this._meshSpaceDirection = meshSpaceDirection.clone();
  88268. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  88269. }
  88270. else {
  88271. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  88272. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  88273. }
  88274. if (!this._updateToMeshFunction) {
  88275. this._updateToMeshFunction = this._updateToMesh.bind(this);
  88276. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  88277. }
  88278. this._updateToMesh();
  88279. };
  88280. RayHelper.prototype.detachFromMesh = function () {
  88281. if (this._attachedToMesh) {
  88282. if (this._updateToMeshFunction) {
  88283. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  88284. }
  88285. this._attachedToMesh = null;
  88286. this._updateToMeshFunction = null;
  88287. }
  88288. };
  88289. RayHelper.prototype._updateToMesh = function () {
  88290. var ray = this.ray;
  88291. if (!this._attachedToMesh || !ray) {
  88292. return;
  88293. }
  88294. if (this._attachedToMesh._isDisposed) {
  88295. this.detachFromMesh();
  88296. return;
  88297. }
  88298. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88299. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88300. };
  88301. RayHelper.prototype.dispose = function () {
  88302. this.hide();
  88303. this.detachFromMesh();
  88304. this.ray = null;
  88305. };
  88306. return RayHelper;
  88307. }());
  88308. BABYLON.RayHelper = RayHelper;
  88309. })(BABYLON || (BABYLON = {}));
  88310. //# sourceMappingURL=babylon.rayHelper.js.map
  88311. var BABYLON;
  88312. (function (BABYLON) {
  88313. // load the inspector using require, if not present in the global namespace.
  88314. var DebugLayer = /** @class */ (function () {
  88315. function DebugLayer(scene) {
  88316. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88317. this._scene = scene;
  88318. // load inspector using require, if it doesn't exist on the global namespace.
  88319. }
  88320. /** Creates the inspector window. */
  88321. DebugLayer.prototype._createInspector = function (config) {
  88322. if (config === void 0) { config = {}; }
  88323. var popup = config.popup || false;
  88324. var initialTab = config.initialTab || 0;
  88325. var parentElement = config.parentElement || null;
  88326. if (!this._inspector) {
  88327. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88328. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88329. } // else nothing to do,; instance is already existing
  88330. };
  88331. DebugLayer.prototype.isVisible = function () {
  88332. if (!this._inspector) {
  88333. return false;
  88334. }
  88335. return true;
  88336. };
  88337. DebugLayer.prototype.hide = function () {
  88338. if (this._inspector) {
  88339. try {
  88340. this._inspector.dispose();
  88341. }
  88342. catch (e) {
  88343. // If the inspector has been removed directly from the inspector tool
  88344. }
  88345. this.onPropertyChangedObservable.clear();
  88346. this._inspector = null;
  88347. }
  88348. };
  88349. /**
  88350. *
  88351. * Launch the debugLayer.
  88352. *
  88353. * initialTab:
  88354. * | Value | Tab Name |
  88355. * | --- | --- |
  88356. * | 0 | Scene |
  88357. * | 1 | Console |
  88358. * | 2 | Stats |
  88359. * | 3 | Textures |
  88360. * | 4 | Mesh |
  88361. * | 5 | Light |
  88362. * | 6 | Material |
  88363. * | 7 | GLTF |
  88364. * | 8 | GUI |
  88365. * | 9 | Physics |
  88366. * | 10 | Camera |
  88367. * | 11 | Audio |
  88368. *
  88369. */
  88370. DebugLayer.prototype.show = function (config) {
  88371. if (config === void 0) { config = {}; }
  88372. if (typeof this.BJSINSPECTOR == 'undefined') {
  88373. // Load inspector and add it to the DOM
  88374. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88375. }
  88376. else {
  88377. // Otherwise creates the inspector
  88378. this._createInspector(config);
  88379. this.onPropertyChangedObservable = new BABYLON.Observable();
  88380. }
  88381. };
  88382. /**
  88383. * Gets the active tab
  88384. * @return the index of the active tab or -1 if the inspector is hidden
  88385. */
  88386. DebugLayer.prototype.getActiveTab = function () {
  88387. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88388. };
  88389. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88390. return DebugLayer;
  88391. }());
  88392. BABYLON.DebugLayer = DebugLayer;
  88393. })(BABYLON || (BABYLON = {}));
  88394. //# sourceMappingURL=babylon.debugLayer.js.map
  88395. var BABYLON;
  88396. (function (BABYLON) {
  88397. var Debug;
  88398. (function (Debug) {
  88399. /**
  88400. * Used to show the physics impostor around the specific mesh
  88401. */
  88402. var PhysicsViewer = /** @class */ (function () {
  88403. /**
  88404. * Creates a new PhysicsViewer
  88405. * @param scene defines the hosting scene
  88406. */
  88407. function PhysicsViewer(scene) {
  88408. /** @hidden */
  88409. this._impostors = [];
  88410. /** @hidden */
  88411. this._meshes = [];
  88412. /** @hidden */
  88413. this._numMeshes = 0;
  88414. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88415. var physicEngine = this._scene.getPhysicsEngine();
  88416. if (physicEngine) {
  88417. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88418. }
  88419. }
  88420. /** @hidden */
  88421. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88422. var plugin = this._physicsEnginePlugin;
  88423. for (var i = 0; i < this._numMeshes; i++) {
  88424. var impostor = this._impostors[i];
  88425. if (!impostor) {
  88426. continue;
  88427. }
  88428. if (impostor.isDisposed) {
  88429. this.hideImpostor(this._impostors[i--]);
  88430. }
  88431. else {
  88432. var mesh = this._meshes[i];
  88433. if (mesh && plugin) {
  88434. plugin.syncMeshWithImpostor(mesh, impostor);
  88435. }
  88436. }
  88437. }
  88438. };
  88439. /**
  88440. * Renders a specified physic impostor
  88441. * @param impostor defines the impostor to render
  88442. */
  88443. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88444. if (!this._scene) {
  88445. return;
  88446. }
  88447. for (var i = 0; i < this._numMeshes; i++) {
  88448. if (this._impostors[i] == impostor) {
  88449. return;
  88450. }
  88451. }
  88452. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88453. if (debugMesh) {
  88454. this._impostors[this._numMeshes] = impostor;
  88455. this._meshes[this._numMeshes] = debugMesh;
  88456. if (this._numMeshes === 0) {
  88457. this._renderFunction = this._updateDebugMeshes.bind(this);
  88458. this._scene.registerBeforeRender(this._renderFunction);
  88459. }
  88460. this._numMeshes++;
  88461. }
  88462. };
  88463. /**
  88464. * Hides a specified physic impostor
  88465. * @param impostor defines the impostor to hide
  88466. */
  88467. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88468. if (!impostor || !this._scene) {
  88469. return;
  88470. }
  88471. var removed = false;
  88472. for (var i = 0; i < this._numMeshes; i++) {
  88473. if (this._impostors[i] == impostor) {
  88474. var mesh = this._meshes[i];
  88475. if (!mesh) {
  88476. continue;
  88477. }
  88478. this._scene.removeMesh(mesh);
  88479. mesh.dispose();
  88480. this._numMeshes--;
  88481. if (this._numMeshes > 0) {
  88482. this._meshes[i] = this._meshes[this._numMeshes];
  88483. this._impostors[i] = this._impostors[this._numMeshes];
  88484. this._meshes[this._numMeshes] = null;
  88485. this._impostors[this._numMeshes] = null;
  88486. }
  88487. else {
  88488. this._meshes[0] = null;
  88489. this._impostors[0] = null;
  88490. }
  88491. removed = true;
  88492. break;
  88493. }
  88494. }
  88495. if (removed && this._numMeshes === 0) {
  88496. this._scene.unregisterBeforeRender(this._renderFunction);
  88497. }
  88498. };
  88499. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88500. if (!this._debugMaterial) {
  88501. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88502. this._debugMaterial.wireframe = true;
  88503. }
  88504. return this._debugMaterial;
  88505. };
  88506. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88507. if (!this._debugBoxMesh) {
  88508. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88509. this._debugBoxMesh.renderingGroupId = 1;
  88510. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88511. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88512. scene.removeMesh(this._debugBoxMesh);
  88513. }
  88514. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88515. };
  88516. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88517. if (!this._debugSphereMesh) {
  88518. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88519. this._debugSphereMesh.renderingGroupId = 1;
  88520. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88521. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88522. scene.removeMesh(this._debugSphereMesh);
  88523. }
  88524. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88525. };
  88526. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88527. var mesh = null;
  88528. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88529. mesh = this._getDebugBoxMesh(scene);
  88530. impostor.getBoxSizeToRef(mesh.scaling);
  88531. }
  88532. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88533. mesh = this._getDebugSphereMesh(scene);
  88534. var radius = impostor.getRadius();
  88535. mesh.scaling.x = radius * 2;
  88536. mesh.scaling.y = radius * 2;
  88537. mesh.scaling.z = radius * 2;
  88538. }
  88539. return mesh;
  88540. };
  88541. /** Releases all resources */
  88542. PhysicsViewer.prototype.dispose = function () {
  88543. for (var i = 0; i < this._numMeshes; i++) {
  88544. this.hideImpostor(this._impostors[i]);
  88545. }
  88546. if (this._debugBoxMesh) {
  88547. this._debugBoxMesh.dispose();
  88548. }
  88549. if (this._debugSphereMesh) {
  88550. this._debugSphereMesh.dispose();
  88551. }
  88552. if (this._debugMaterial) {
  88553. this._debugMaterial.dispose();
  88554. }
  88555. this._impostors.length = 0;
  88556. this._scene = null;
  88557. this._physicsEnginePlugin = null;
  88558. };
  88559. return PhysicsViewer;
  88560. }());
  88561. Debug.PhysicsViewer = PhysicsViewer;
  88562. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88563. })(BABYLON || (BABYLON = {}));
  88564. //# sourceMappingURL=babylon.physicsViewer.js.map
  88565. var BABYLON;
  88566. (function (BABYLON) {
  88567. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  88568. get: function () {
  88569. return this._forceShowBoundingBoxes || false;
  88570. },
  88571. set: function (value) {
  88572. this._forceShowBoundingBoxes = value;
  88573. // Lazyly creates a BB renderer if needed.
  88574. if (value) {
  88575. this.getBoundingBoxRenderer();
  88576. }
  88577. },
  88578. enumerable: true,
  88579. configurable: true
  88580. });
  88581. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  88582. if (!this._boundingBoxRenderer) {
  88583. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  88584. }
  88585. return this._boundingBoxRenderer;
  88586. };
  88587. var BoundingBoxRenderer = /** @class */ (function () {
  88588. function BoundingBoxRenderer(scene) {
  88589. /**
  88590. * The component name helpfull to identify the component in the list of scene components.
  88591. */
  88592. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  88593. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88594. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88595. this.showBackLines = true;
  88596. this.renderList = new BABYLON.SmartArray(32);
  88597. this._vertexBuffers = {};
  88598. this.scene = scene;
  88599. scene._addComponent(this);
  88600. }
  88601. /**
  88602. * Registers the component in a given scene
  88603. */
  88604. BoundingBoxRenderer.prototype.register = function () {
  88605. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  88606. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  88607. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  88608. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  88609. };
  88610. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  88611. if (mesh.showSubMeshesBoundingBox) {
  88612. var boundingInfo = subMesh.getBoundingInfo();
  88613. if (boundingInfo !== null && boundingInfo !== undefined) {
  88614. this.renderList.push(boundingInfo.boundingBox);
  88615. }
  88616. }
  88617. };
  88618. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  88619. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  88620. var boundingInfo = sourceMesh.getBoundingInfo();
  88621. this.renderList.push(boundingInfo.boundingBox);
  88622. }
  88623. };
  88624. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88625. if (this._colorShader) {
  88626. return;
  88627. }
  88628. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  88629. attributes: [BABYLON.VertexBuffer.PositionKind],
  88630. uniforms: ["world", "viewProjection", "color"]
  88631. });
  88632. var engine = this.scene.getEngine();
  88633. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88634. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88635. this._createIndexBuffer();
  88636. };
  88637. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88638. var engine = this.scene.getEngine();
  88639. 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]);
  88640. };
  88641. /**
  88642. * Rebuilds the elements related to this component in case of
  88643. * context lost for instance.
  88644. */
  88645. BoundingBoxRenderer.prototype.rebuild = function () {
  88646. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88647. if (vb) {
  88648. vb._rebuild();
  88649. }
  88650. this._createIndexBuffer();
  88651. };
  88652. BoundingBoxRenderer.prototype.reset = function () {
  88653. this.renderList.reset();
  88654. };
  88655. BoundingBoxRenderer.prototype.render = function () {
  88656. if (this.renderList.length === 0) {
  88657. return;
  88658. }
  88659. this._prepareRessources();
  88660. if (!this._colorShader.isReady()) {
  88661. return;
  88662. }
  88663. var engine = this.scene.getEngine();
  88664. engine.setDepthWrite(false);
  88665. this._colorShader._preBind();
  88666. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88667. var boundingBox = this.renderList.data[boundingBoxIndex];
  88668. var min = boundingBox.minimum;
  88669. var max = boundingBox.maximum;
  88670. var diff = max.subtract(min);
  88671. var median = min.add(diff.scale(0.5));
  88672. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88673. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88674. .multiply(boundingBox.getWorldMatrix());
  88675. // VBOs
  88676. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88677. if (this.showBackLines) {
  88678. // Back
  88679. engine.setDepthFunctionToGreaterOrEqual();
  88680. this.scene.resetCachedMaterial();
  88681. this._colorShader.setColor4("color", this.backColor.toColor4());
  88682. this._colorShader.bind(worldMatrix);
  88683. // Draw order
  88684. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88685. }
  88686. // Front
  88687. engine.setDepthFunctionToLess();
  88688. this.scene.resetCachedMaterial();
  88689. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88690. this._colorShader.bind(worldMatrix);
  88691. // Draw order
  88692. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88693. }
  88694. this._colorShader.unbind();
  88695. engine.setDepthFunctionToLessOrEqual();
  88696. engine.setDepthWrite(true);
  88697. };
  88698. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88699. this._prepareRessources();
  88700. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88701. return;
  88702. }
  88703. var engine = this.scene.getEngine();
  88704. engine.setDepthWrite(false);
  88705. engine.setColorWrite(false);
  88706. this._colorShader._preBind();
  88707. var boundingBox = mesh._boundingInfo.boundingBox;
  88708. var min = boundingBox.minimum;
  88709. var max = boundingBox.maximum;
  88710. var diff = max.subtract(min);
  88711. var median = min.add(diff.scale(0.5));
  88712. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88713. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88714. .multiply(boundingBox.getWorldMatrix());
  88715. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88716. engine.setDepthFunctionToLess();
  88717. this.scene.resetCachedMaterial();
  88718. this._colorShader.bind(worldMatrix);
  88719. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88720. this._colorShader.unbind();
  88721. engine.setDepthFunctionToLessOrEqual();
  88722. engine.setDepthWrite(true);
  88723. engine.setColorWrite(true);
  88724. };
  88725. BoundingBoxRenderer.prototype.dispose = function () {
  88726. if (!this._colorShader) {
  88727. return;
  88728. }
  88729. this.renderList.dispose();
  88730. this._colorShader.dispose();
  88731. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88732. if (buffer) {
  88733. buffer.dispose();
  88734. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88735. }
  88736. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  88737. };
  88738. return BoundingBoxRenderer;
  88739. }());
  88740. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88741. })(BABYLON || (BABYLON = {}));
  88742. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88743. var BABYLON;
  88744. (function (BABYLON) {
  88745. /**
  88746. * Renders a layer on top of an existing scene
  88747. */
  88748. var UtilityLayerRenderer = /** @class */ (function () {
  88749. /**
  88750. * Instantiates a UtilityLayerRenderer
  88751. * @param originalScene the original scene that will be rendered on top of
  88752. */
  88753. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88754. var _this = this;
  88755. this.originalScene = originalScene;
  88756. this._pointerCaptures = {};
  88757. this._lastPointerEvents = {};
  88758. /**
  88759. * If the utility layer should automatically be rendered on top of existing scene
  88760. */
  88761. this.shouldRender = true;
  88762. /**
  88763. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88764. */
  88765. this.onlyCheckPointerDownEvents = true;
  88766. /**
  88767. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88768. */
  88769. this.processAllEvents = false;
  88770. /**
  88771. * Observable raised when the pointer move from the utility layer scene to the main scene
  88772. */
  88773. this.onPointerOutObservable = new BABYLON.Observable();
  88774. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88775. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88776. originalScene.getEngine().scenes.pop();
  88777. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88778. this.utilityLayerScene.detachControl();
  88779. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88780. if (!_this.processAllEvents) {
  88781. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88782. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88783. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88784. return;
  88785. }
  88786. }
  88787. var pointerEvent = (prePointerInfo.event);
  88788. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88789. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88790. return;
  88791. }
  88792. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88793. if (!prePointerInfo.ray && utilityScenePick) {
  88794. prePointerInfo.ray = utilityScenePick.ray;
  88795. }
  88796. // always fire the prepointer oversvable
  88797. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88798. // allow every non pointer down event to flow to the utility layer
  88799. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88800. if (!prePointerInfo.skipOnPointerObservable) {
  88801. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88802. }
  88803. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88804. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88805. }
  88806. return;
  88807. }
  88808. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88809. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88810. if (utilityScenePick && utilityScenePick.hit) {
  88811. if (!prePointerInfo.skipOnPointerObservable) {
  88812. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88813. }
  88814. prePointerInfo.skipOnPointerObservable = true;
  88815. }
  88816. }
  88817. else {
  88818. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88819. var pointerEvent_1 = (prePointerInfo.event);
  88820. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88821. if (originalScenePick && utilityScenePick) {
  88822. // No pick in utility scene
  88823. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88824. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88825. // We touched an utility mesh present in the main scene
  88826. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88827. prePointerInfo.skipOnPointerObservable = true;
  88828. }
  88829. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88830. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88831. }
  88832. }
  88833. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88834. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88835. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88836. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88837. }
  88838. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88839. // We have a pick in both scenes but main is closer than utility
  88840. // We touched an utility mesh present in the main scene
  88841. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88842. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88843. prePointerInfo.skipOnPointerObservable = true;
  88844. }
  88845. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88846. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88847. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88848. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88849. }
  88850. }
  88851. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88852. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88853. }
  88854. }
  88855. }
  88856. });
  88857. // Render directly on top of existing scene without clearing
  88858. this.utilityLayerScene.autoClear = false;
  88859. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88860. if (_this.shouldRender) {
  88861. _this.render();
  88862. }
  88863. });
  88864. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88865. _this.dispose();
  88866. });
  88867. this._updateCamera();
  88868. }
  88869. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88870. get: function () {
  88871. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88872. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88873. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88874. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88875. });
  88876. }
  88877. return UtilityLayerRenderer._DefaultUtilityLayer;
  88878. },
  88879. enumerable: true,
  88880. configurable: true
  88881. });
  88882. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88883. if (!prePointerInfo.skipOnPointerObservable) {
  88884. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88885. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88886. }
  88887. };
  88888. /**
  88889. * Renders the utility layers scene on top of the original scene
  88890. */
  88891. UtilityLayerRenderer.prototype.render = function () {
  88892. this._updateCamera();
  88893. this.utilityLayerScene.render(false);
  88894. };
  88895. /**
  88896. * Disposes of the renderer
  88897. */
  88898. UtilityLayerRenderer.prototype.dispose = function () {
  88899. this.onPointerOutObservable.clear();
  88900. if (this._afterRenderObserver) {
  88901. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88902. }
  88903. if (this._sceneDisposeObserver) {
  88904. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88905. }
  88906. if (this._originalPointerObserver) {
  88907. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88908. }
  88909. this.utilityLayerScene.dispose();
  88910. };
  88911. UtilityLayerRenderer.prototype._updateCamera = function () {
  88912. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88913. };
  88914. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88915. return UtilityLayerRenderer;
  88916. }());
  88917. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88918. })(BABYLON || (BABYLON = {}));
  88919. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88920. //# sourceMappingURL=babylon.behavior.js.map
  88921. var BABYLON;
  88922. (function (BABYLON) {
  88923. /**
  88924. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88925. */
  88926. var PointerDragBehavior = /** @class */ (function () {
  88927. /**
  88928. * Creates a pointer drag behavior that can be attached to a mesh
  88929. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  88930. */
  88931. function PointerDragBehavior(options) {
  88932. this.options = options;
  88933. /**
  88934. * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
  88935. */
  88936. this.maxDragAngle = 0;
  88937. /**
  88938. * @hidden
  88939. */
  88940. this._useAlternatePickedPointAboveMaxDragAngle = false;
  88941. /**
  88942. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88943. */
  88944. this.currentDraggingPointerID = -1;
  88945. /**
  88946. * If the behavior is currently in a dragging state
  88947. */
  88948. this.dragging = false;
  88949. /**
  88950. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88951. */
  88952. this.dragDeltaRatio = 0.2;
  88953. /**
  88954. * If the drag plane orientation should be updated during the dragging (Default: true)
  88955. */
  88956. this.updateDragPlane = true;
  88957. // Debug mode will display drag planes to help visualize behavior
  88958. this._debugMode = false;
  88959. this._moving = false;
  88960. /**
  88961. * Fires each time the attached mesh is dragged with the pointer
  88962. * * delta between last drag position and current drag position in world space
  88963. * * dragDistance along the drag axis
  88964. * * dragPlaneNormal normal of the current drag plane used during the drag
  88965. * * dragPlanePoint in world space where the drag intersects the drag plane
  88966. */
  88967. this.onDragObservable = new BABYLON.Observable();
  88968. /**
  88969. * Fires each time a drag begins (eg. mouse down on mesh)
  88970. */
  88971. this.onDragStartObservable = new BABYLON.Observable();
  88972. /**
  88973. * Fires each time a drag ends (eg. mouse release after drag)
  88974. */
  88975. this.onDragEndObservable = new BABYLON.Observable();
  88976. /**
  88977. * If the attached mesh should be moved when dragged
  88978. */
  88979. this.moveAttached = true;
  88980. /**
  88981. * If the drag behavior will react to drag events (Default: true)
  88982. */
  88983. this.enabled = true;
  88984. /**
  88985. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88986. */
  88987. this.useObjectOrienationForDragging = true;
  88988. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88989. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  88990. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88991. // Variables to avoid instantiation in the below method
  88992. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88993. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88994. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88995. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88996. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88997. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88998. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88999. var optionCount = 0;
  89000. if (options === undefined) {
  89001. options = {};
  89002. }
  89003. if (options.dragAxis) {
  89004. optionCount++;
  89005. }
  89006. if (options.dragPlaneNormal) {
  89007. optionCount++;
  89008. }
  89009. if (optionCount > 1) {
  89010. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  89011. }
  89012. }
  89013. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  89014. /**
  89015. * The name of the behavior
  89016. */
  89017. get: function () {
  89018. return "PointerDrag";
  89019. },
  89020. enumerable: true,
  89021. configurable: true
  89022. });
  89023. /**
  89024. * Initializes the behavior
  89025. */
  89026. PointerDragBehavior.prototype.init = function () { };
  89027. /**
  89028. * Attaches the drag behavior the passed in mesh
  89029. * @param ownerNode The mesh that will be dragged around once attached
  89030. */
  89031. PointerDragBehavior.prototype.attach = function (ownerNode) {
  89032. var _this = this;
  89033. this._scene = ownerNode.getScene();
  89034. this._attachedNode = ownerNode;
  89035. // Initialize drag plane to not interfere with existing scene
  89036. if (!PointerDragBehavior._planeScene) {
  89037. if (this._debugMode) {
  89038. PointerDragBehavior._planeScene = this._scene;
  89039. }
  89040. else {
  89041. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  89042. this._scene.getEngine().scenes.pop();
  89043. }
  89044. }
  89045. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  89046. // State of the drag
  89047. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  89048. var delta = new BABYLON.Vector3(0, 0, 0);
  89049. var dragLength = 0;
  89050. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  89051. var pickPredicate = function (m) {
  89052. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  89053. };
  89054. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89055. if (!_this.enabled) {
  89056. return;
  89057. }
  89058. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89059. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89060. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  89061. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89062. if (pickedPoint) {
  89063. _this.dragging = true;
  89064. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89065. _this.lastDragPosition.copyFrom(pickedPoint);
  89066. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  89067. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  89068. }
  89069. }
  89070. }
  89071. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89072. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89073. _this.releaseDrag();
  89074. }
  89075. }
  89076. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89077. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89078. _this._moving = true;
  89079. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  89080. if (pickedPoint) {
  89081. if (_this.updateDragPlane) {
  89082. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  89083. }
  89084. // depending on the drag mode option drag accordingly
  89085. if (_this.options.dragAxis) {
  89086. // Convert local drag axis to world
  89087. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  89088. // Project delta drag from the drag plane onto the drag axis
  89089. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  89090. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  89091. _this._worldDragAxis.scaleToRef(dragLength, delta);
  89092. }
  89093. else {
  89094. dragLength = delta.length();
  89095. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  89096. }
  89097. targetPosition.addInPlace(delta);
  89098. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  89099. _this.lastDragPosition.copyFrom(pickedPoint);
  89100. }
  89101. }
  89102. }
  89103. });
  89104. this._scene.onBeforeRenderObservable.add(function () {
  89105. if (_this._moving && _this.moveAttached) {
  89106. // Slowly move mesh to avoid jitter
  89107. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  89108. _this._tmpVector.scaleInPlace(0.2);
  89109. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  89110. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  89111. }
  89112. });
  89113. };
  89114. PointerDragBehavior.prototype.releaseDrag = function () {
  89115. this.dragging = false;
  89116. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  89117. this.currentDraggingPointerID = -1;
  89118. this._moving = false;
  89119. };
  89120. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  89121. var _this = this;
  89122. if (!ray) {
  89123. return null;
  89124. }
  89125. // Calculate angle between plane normal and ray
  89126. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  89127. // Correct if ray is casted from oposite side
  89128. if (angle > Math.PI / 2) {
  89129. angle = Math.PI - angle;
  89130. }
  89131. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  89132. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  89133. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  89134. // Invert ray direction along the towards object axis
  89135. this._tmpVector.copyFrom(ray.direction);
  89136. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  89137. this._alternatePickedPoint.normalize();
  89138. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  89139. this._tmpVector.addInPlace(this._alternatePickedPoint);
  89140. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  89141. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  89142. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  89143. this._alternatePickedPoint.addInPlace(this._tmpVector);
  89144. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  89145. return this._alternatePickedPoint;
  89146. }
  89147. else {
  89148. return null;
  89149. }
  89150. }
  89151. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  89152. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  89153. return pickResult.pickedPoint;
  89154. }
  89155. else {
  89156. return null;
  89157. }
  89158. };
  89159. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  89160. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  89161. this._pointA.copyFrom(dragPlanePosition);
  89162. if (this.options.dragAxis) {
  89163. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  89164. // Calculate plane normal in direction of camera but perpendicular to drag axis
  89165. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  89166. ray.origin.subtractToRef(this._pointA, this._pointC);
  89167. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  89168. // Get perpendicular line from direction to camera and drag axis
  89169. this._pointB.subtractToRef(this._pointA, this._lineA);
  89170. this._pointC.subtractToRef(this._pointA, this._lineB);
  89171. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  89172. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  89173. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  89174. this._lookAt.normalize();
  89175. this._dragPlane.position.copyFrom(this._pointA);
  89176. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  89177. this._dragPlane.lookAt(this._lookAt);
  89178. }
  89179. else if (this.options.dragPlaneNormal) {
  89180. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  89181. this._dragPlane.position.copyFrom(this._pointA);
  89182. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  89183. this._dragPlane.lookAt(this._lookAt);
  89184. }
  89185. else {
  89186. this._dragPlane.position.copyFrom(this._pointA);
  89187. this._dragPlane.lookAt(ray.origin);
  89188. }
  89189. this._dragPlane.computeWorldMatrix(true);
  89190. };
  89191. /**
  89192. * Detaches the behavior from the mesh
  89193. */
  89194. PointerDragBehavior.prototype.detach = function () {
  89195. if (this._pointerObserver) {
  89196. this._scene.onPointerObservable.remove(this._pointerObserver);
  89197. }
  89198. };
  89199. return PointerDragBehavior;
  89200. }());
  89201. BABYLON.PointerDragBehavior = PointerDragBehavior;
  89202. })(BABYLON || (BABYLON = {}));
  89203. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  89204. var BABYLON;
  89205. (function (BABYLON) {
  89206. /**
  89207. * A behavior that when attached to a mesh will allow the mesh to be scaled
  89208. */
  89209. var MultiPointerScaleBehavior = /** @class */ (function () {
  89210. function MultiPointerScaleBehavior() {
  89211. this._startDistance = 0;
  89212. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  89213. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  89214. this._sceneRenderObserver = null;
  89215. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  89216. this._dragBehaviorA.moveAttached = false;
  89217. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  89218. this._dragBehaviorB.moveAttached = false;
  89219. }
  89220. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  89221. /**
  89222. * The name of the behavior
  89223. */
  89224. get: function () {
  89225. return "MultiPointerScale";
  89226. },
  89227. enumerable: true,
  89228. configurable: true
  89229. });
  89230. /**
  89231. * Initializes the behavior
  89232. */
  89233. MultiPointerScaleBehavior.prototype.init = function () { };
  89234. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  89235. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  89236. };
  89237. /**
  89238. * Attaches the scale behavior the passed in mesh
  89239. * @param ownerNode The mesh that will be scaled around once attached
  89240. */
  89241. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  89242. var _this = this;
  89243. this._ownerNode = ownerNode;
  89244. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  89245. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  89246. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89247. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89248. _this._dragBehaviorA.releaseDrag();
  89249. }
  89250. else {
  89251. _this._initialScale.copyFrom(ownerNode.scaling);
  89252. _this._startDistance = _this._getCurrentDistance();
  89253. }
  89254. }
  89255. });
  89256. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  89257. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89258. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  89259. _this._dragBehaviorB.releaseDrag();
  89260. }
  89261. else {
  89262. _this._initialScale.copyFrom(ownerNode.scaling);
  89263. _this._startDistance = _this._getCurrentDistance();
  89264. }
  89265. }
  89266. });
  89267. // Once both drag behaviors are active scale based on the distance between the two pointers
  89268. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89269. behavior.onDragObservable.add(function () {
  89270. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89271. var ratio = _this._getCurrentDistance() / _this._startDistance;
  89272. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  89273. }
  89274. });
  89275. });
  89276. ownerNode.addBehavior(this._dragBehaviorA);
  89277. ownerNode.addBehavior(this._dragBehaviorB);
  89278. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89279. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89280. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  89281. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  89282. if (change.length() > 0.01) {
  89283. ownerNode.scaling.addInPlace(change);
  89284. }
  89285. }
  89286. });
  89287. };
  89288. /**
  89289. * Detaches the behavior from the mesh
  89290. */
  89291. MultiPointerScaleBehavior.prototype.detach = function () {
  89292. var _this = this;
  89293. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89294. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  89295. behavior.onDragStartObservable.clear();
  89296. behavior.onDragObservable.clear();
  89297. _this._ownerNode.removeBehavior(behavior);
  89298. });
  89299. };
  89300. return MultiPointerScaleBehavior;
  89301. }());
  89302. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  89303. })(BABYLON || (BABYLON = {}));
  89304. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  89305. var BABYLON;
  89306. (function (BABYLON) {
  89307. /**
  89308. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  89309. */
  89310. var SixDofDragBehavior = /** @class */ (function () {
  89311. function SixDofDragBehavior() {
  89312. this._sceneRenderObserver = null;
  89313. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  89314. this._moving = false;
  89315. this._startingOrientation = new BABYLON.Quaternion();
  89316. /**
  89317. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  89318. */
  89319. this.zDragFactor = 5;
  89320. /**
  89321. * If the behavior is currently in a dragging state
  89322. */
  89323. this.dragging = false;
  89324. /**
  89325. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  89326. */
  89327. this.dragDeltaRatio = 0.2;
  89328. /**
  89329. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  89330. */
  89331. this.currentDraggingPointerID = -1;
  89332. }
  89333. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  89334. /**
  89335. * The name of the behavior
  89336. */
  89337. get: function () {
  89338. return "SixDofDrag";
  89339. },
  89340. enumerable: true,
  89341. configurable: true
  89342. });
  89343. /**
  89344. * Initializes the behavior
  89345. */
  89346. SixDofDragBehavior.prototype.init = function () { };
  89347. /**
  89348. * Attaches the scale behavior the passed in mesh
  89349. * @param ownerNode The mesh that will be scaled around once attached
  89350. */
  89351. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  89352. var _this = this;
  89353. this._ownerNode = ownerNode;
  89354. this._scene = this._ownerNode.getScene();
  89355. if (!SixDofDragBehavior._virtualScene) {
  89356. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  89357. this._scene.getEngine().scenes.pop();
  89358. }
  89359. var pickedMesh = null;
  89360. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  89361. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  89362. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89363. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  89364. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  89365. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  89366. var pickPredicate = function (m) {
  89367. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  89368. };
  89369. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  89370. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89371. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  89372. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  89373. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89374. // Set position and orientation of the controller
  89375. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89376. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89377. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  89378. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89379. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  89380. if (!pickedMesh.rotationQuaternion) {
  89381. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89382. }
  89383. var oldParent = pickedMesh.parent;
  89384. pickedMesh.setParent(null);
  89385. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89386. pickedMesh.setParent(oldParent);
  89387. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89388. // Update state
  89389. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89390. _this.dragging = true;
  89391. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89392. }
  89393. }
  89394. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89395. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89396. _this.dragging = false;
  89397. _this._moving = false;
  89398. _this.currentDraggingPointerID = -1;
  89399. pickedMesh = null;
  89400. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89401. }
  89402. }
  89403. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89404. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89405. // Calculate controller drag distance in controller space
  89406. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89407. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89408. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  89409. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89410. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89411. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  89412. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  89413. if (_this._virtualDragMesh.position.z < 0) {
  89414. _this._virtualDragMesh.position.z = 0;
  89415. }
  89416. // Update the controller position
  89417. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89418. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89419. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89420. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89421. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89422. if (pickedMesh.parent) {
  89423. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89424. }
  89425. if (!_this._moving) {
  89426. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89427. }
  89428. _this._moving = true;
  89429. }
  89430. }
  89431. });
  89432. var tmpQuaternion = new BABYLON.Quaternion();
  89433. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89434. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89435. if (_this.dragging && _this._moving && pickedMesh) {
  89436. // Slowly move mesh to avoid jitter
  89437. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89438. // Get change in rotation
  89439. tmpQuaternion.copyFrom(_this._startingOrientation);
  89440. tmpQuaternion.x = -tmpQuaternion.x;
  89441. tmpQuaternion.y = -tmpQuaternion.y;
  89442. tmpQuaternion.z = -tmpQuaternion.z;
  89443. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89444. // Convert change in rotation to only y axis rotation
  89445. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89446. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89447. // Slowly move mesh to avoid jitter
  89448. var oldParent = pickedMesh.parent;
  89449. pickedMesh.setParent(null);
  89450. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89451. pickedMesh.setParent(oldParent);
  89452. }
  89453. });
  89454. };
  89455. /**
  89456. * Detaches the behavior from the mesh
  89457. */
  89458. SixDofDragBehavior.prototype.detach = function () {
  89459. this._scene.onPointerObservable.remove(this._pointerObserver);
  89460. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89461. this._virtualOriginMesh.dispose();
  89462. this._virtualDragMesh.dispose();
  89463. };
  89464. return SixDofDragBehavior;
  89465. }());
  89466. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89467. })(BABYLON || (BABYLON = {}));
  89468. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89469. var BABYLON;
  89470. (function (BABYLON) {
  89471. /**
  89472. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89473. */
  89474. var Gizmo = /** @class */ (function () {
  89475. /**
  89476. * Creates a gizmo
  89477. * @param gizmoLayer The utility layer the gizmo will be added to
  89478. */
  89479. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89480. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89481. var _this = this;
  89482. this.gizmoLayer = gizmoLayer;
  89483. this._scaleFactor = 3;
  89484. this._tmpMatrix = new BABYLON.Matrix();
  89485. /**
  89486. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89487. */
  89488. this.updateGizmoRotationToMatchAttachedMesh = true;
  89489. /**
  89490. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89491. */
  89492. this.updateGizmoPositionToMatchAttachedMesh = true;
  89493. /**
  89494. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89495. */
  89496. this._updateScale = true;
  89497. this._interactionsEnabled = true;
  89498. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89499. var tempVector = new BABYLON.Vector3();
  89500. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89501. if (_this.attachedMesh) {
  89502. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89503. if (!_this._rootMesh.rotationQuaternion) {
  89504. _this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._rootMesh.rotation.y, _this._rootMesh.rotation.x, _this._rootMesh.rotation.z);
  89505. }
  89506. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  89507. tempVector.copyFrom(_this.attachedMesh.scaling);
  89508. if (_this.attachedMesh.scaling.x < 0) {
  89509. _this.attachedMesh.scaling.x *= -1;
  89510. }
  89511. if (_this.attachedMesh.scaling.y < 0) {
  89512. _this.attachedMesh.scaling.y *= -1;
  89513. }
  89514. if (_this.attachedMesh.scaling.z < 0) {
  89515. _this.attachedMesh.scaling.z *= -1;
  89516. }
  89517. _this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  89518. _this.attachedMesh.scaling.copyFrom(tempVector);
  89519. _this.attachedMesh.computeWorldMatrix();
  89520. BABYLON.Quaternion.FromRotationMatrixToRef(_this._tmpMatrix, _this._rootMesh.rotationQuaternion);
  89521. }
  89522. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89523. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89524. }
  89525. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89526. _this._rootMesh.position.subtractToRef(_this.gizmoLayer.utilityLayerScene.activeCamera.position, tempVector);
  89527. var dist = tempVector.length() / _this._scaleFactor;
  89528. _this._rootMesh.scaling.set(dist, dist, dist);
  89529. }
  89530. }
  89531. });
  89532. this.attachedMesh = null;
  89533. }
  89534. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89535. /**
  89536. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89537. * * When set, interactions will be enabled
  89538. */
  89539. get: function () {
  89540. return this._attachedMesh;
  89541. },
  89542. set: function (value) {
  89543. this._attachedMesh = value;
  89544. this._rootMesh.setEnabled(value ? true : false);
  89545. this._attachedMeshChanged(value);
  89546. },
  89547. enumerable: true,
  89548. configurable: true
  89549. });
  89550. Gizmo.prototype._attachedMeshChanged = function (value) {
  89551. };
  89552. /**
  89553. * Disposes of the gizmo
  89554. */
  89555. Gizmo.prototype.dispose = function () {
  89556. this._rootMesh.dispose();
  89557. if (this._beforeRenderObserver) {
  89558. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89559. }
  89560. };
  89561. return Gizmo;
  89562. }());
  89563. BABYLON.Gizmo = Gizmo;
  89564. })(BABYLON || (BABYLON = {}));
  89565. //# sourceMappingURL=babylon.gizmo.js.map
  89566. var BABYLON;
  89567. (function (BABYLON) {
  89568. /**
  89569. * Single axis drag gizmo
  89570. */
  89571. var AxisDragGizmo = /** @class */ (function (_super) {
  89572. __extends(AxisDragGizmo, _super);
  89573. /**
  89574. * Creates an AxisDragGizmo
  89575. * @param gizmoLayer The utility layer the gizmo will be added to
  89576. * @param dragAxis The axis which the gizmo will be able to drag on
  89577. * @param color The color of the gizmo
  89578. */
  89579. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89580. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89581. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89582. var _this = _super.call(this, gizmoLayer) || this;
  89583. _this._pointerObserver = null;
  89584. /**
  89585. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89586. */
  89587. _this.snapDistance = 0;
  89588. /**
  89589. * Event that fires each time the gizmo snaps to a new location.
  89590. * * snapDistance is the the change in distance
  89591. */
  89592. _this.onSnapObservable = new BABYLON.Observable();
  89593. // Create Material
  89594. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89595. coloredMaterial.disableLighting = true;
  89596. coloredMaterial.emissiveColor = color;
  89597. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89598. hoverMaterial.disableLighting = true;
  89599. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89600. // Build mesh on root node
  89601. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89602. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89603. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89604. arrow.addChild(arrowMesh);
  89605. arrow.addChild(arrowTail);
  89606. // Position arrow pointing in its drag axis
  89607. arrowMesh.scaling.scaleInPlace(0.05);
  89608. arrowMesh.material = coloredMaterial;
  89609. arrowMesh.rotation.x = Math.PI / 2;
  89610. arrowMesh.position.z += 0.3;
  89611. arrowTail.rotation.x = Math.PI / 2;
  89612. arrowTail.material = coloredMaterial;
  89613. arrowTail.position.z += 0.15;
  89614. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89615. _this._rootMesh.addChild(arrow);
  89616. var currentSnapDragDistance = 0;
  89617. var tmpVector = new BABYLON.Vector3();
  89618. var tmpSnapEvent = { snapDistance: 0 };
  89619. // Add drag behavior to handle events when the gizmo is dragged
  89620. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89621. _this.dragBehavior.moveAttached = false;
  89622. _this._rootMesh.addBehavior(_this.dragBehavior);
  89623. _this.dragBehavior.onDragObservable.add(function (event) {
  89624. if (_this.attachedMesh) {
  89625. // Snapping logic
  89626. if (_this.snapDistance == 0) {
  89627. _this.attachedMesh.position.addInPlace(event.delta);
  89628. }
  89629. else {
  89630. currentSnapDragDistance += event.dragDistance;
  89631. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89632. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89633. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89634. event.delta.normalizeToRef(tmpVector);
  89635. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89636. _this.attachedMesh.position.addInPlace(tmpVector);
  89637. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89638. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89639. }
  89640. }
  89641. }
  89642. });
  89643. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89644. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89645. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89646. m.material = hoverMaterial;
  89647. });
  89648. }
  89649. else {
  89650. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89651. m.material = coloredMaterial;
  89652. });
  89653. }
  89654. });
  89655. return _this;
  89656. }
  89657. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89658. if (this.dragBehavior) {
  89659. this.dragBehavior.enabled = value ? true : false;
  89660. }
  89661. };
  89662. /**
  89663. * Disposes of the gizmo
  89664. */
  89665. AxisDragGizmo.prototype.dispose = function () {
  89666. this.onSnapObservable.clear();
  89667. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89668. this.dragBehavior.detach();
  89669. _super.prototype.dispose.call(this);
  89670. };
  89671. return AxisDragGizmo;
  89672. }(BABYLON.Gizmo));
  89673. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89674. })(BABYLON || (BABYLON = {}));
  89675. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89676. var BABYLON;
  89677. (function (BABYLON) {
  89678. /**
  89679. * Single axis scale gizmo
  89680. */
  89681. var AxisScaleGizmo = /** @class */ (function (_super) {
  89682. __extends(AxisScaleGizmo, _super);
  89683. /**
  89684. * Creates an AxisScaleGizmo
  89685. * @param gizmoLayer The utility layer the gizmo will be added to
  89686. * @param dragAxis The axis which the gizmo will be able to scale on
  89687. * @param color The color of the gizmo
  89688. */
  89689. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89690. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89691. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89692. var _this = _super.call(this, gizmoLayer) || this;
  89693. _this._pointerObserver = null;
  89694. /**
  89695. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89696. */
  89697. _this.snapDistance = 0;
  89698. /**
  89699. * Event that fires each time the gizmo snaps to a new location.
  89700. * * snapDistance is the the change in distance
  89701. */
  89702. _this.onSnapObservable = new BABYLON.Observable();
  89703. // Create Material
  89704. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89705. coloredMaterial.disableLighting = true;
  89706. coloredMaterial.emissiveColor = color;
  89707. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89708. hoverMaterial.disableLighting = true;
  89709. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89710. // Build mesh on root node
  89711. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89712. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89713. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89714. arrow.addChild(arrowMesh);
  89715. arrow.addChild(arrowTail);
  89716. // Position arrow pointing in its drag axis
  89717. arrowMesh.scaling.scaleInPlace(0.1);
  89718. arrowMesh.material = coloredMaterial;
  89719. arrowMesh.rotation.x = Math.PI / 2;
  89720. arrowMesh.position.z += 0.3;
  89721. arrowTail.rotation.x = Math.PI / 2;
  89722. arrowTail.material = coloredMaterial;
  89723. arrowTail.position.z += 0.15;
  89724. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89725. _this._rootMesh.addChild(arrow);
  89726. // Add drag behavior to handle events when the gizmo is dragged
  89727. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89728. _this.dragBehavior.moveAttached = false;
  89729. _this._rootMesh.addBehavior(_this.dragBehavior);
  89730. var currentSnapDragDistance = 0;
  89731. var tmpVector = new BABYLON.Vector3();
  89732. var tmpSnapEvent = { snapDistance: 0 };
  89733. _this.dragBehavior.onDragObservable.add(function (event) {
  89734. if (_this.attachedMesh) {
  89735. // Snapping logic
  89736. var snapped = false;
  89737. var dragSteps = 0;
  89738. if (_this.snapDistance == 0) {
  89739. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89740. }
  89741. else {
  89742. currentSnapDragDistance += event.dragDistance;
  89743. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89744. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89745. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89746. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89747. snapped = true;
  89748. }
  89749. else {
  89750. tmpVector.scaleInPlace(0);
  89751. }
  89752. }
  89753. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89754. if (snapped) {
  89755. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89756. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89757. }
  89758. }
  89759. });
  89760. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89761. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89762. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89763. m.material = hoverMaterial;
  89764. });
  89765. }
  89766. else {
  89767. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89768. m.material = coloredMaterial;
  89769. });
  89770. }
  89771. });
  89772. return _this;
  89773. }
  89774. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89775. if (this.dragBehavior) {
  89776. this.dragBehavior.enabled = value ? true : false;
  89777. }
  89778. };
  89779. /**
  89780. * Disposes of the gizmo
  89781. */
  89782. AxisScaleGizmo.prototype.dispose = function () {
  89783. this.onSnapObservable.clear();
  89784. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89785. this.dragBehavior.detach();
  89786. _super.prototype.dispose.call(this);
  89787. };
  89788. return AxisScaleGizmo;
  89789. }(BABYLON.Gizmo));
  89790. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89791. })(BABYLON || (BABYLON = {}));
  89792. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89793. var BABYLON;
  89794. (function (BABYLON) {
  89795. /**
  89796. * Single plane rotation gizmo
  89797. */
  89798. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89799. __extends(PlaneRotationGizmo, _super);
  89800. /**
  89801. * Creates a PlaneRotationGizmo
  89802. * @param gizmoLayer The utility layer the gizmo will be added to
  89803. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89804. * @param color The color of the gizmo
  89805. */
  89806. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89807. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89808. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89809. var _this = _super.call(this, gizmoLayer) || this;
  89810. _this._pointerObserver = null;
  89811. /**
  89812. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89813. */
  89814. _this.snapDistance = 0;
  89815. /**
  89816. * Event that fires each time the gizmo snaps to a new location.
  89817. * * snapDistance is the the change in distance
  89818. */
  89819. _this.onSnapObservable = new BABYLON.Observable();
  89820. // Create Material
  89821. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89822. coloredMaterial.disableLighting = true;
  89823. coloredMaterial.emissiveColor = color;
  89824. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89825. hoverMaterial.disableLighting = true;
  89826. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89827. // Build mesh on root node
  89828. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89829. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89830. // Position arrow pointing in its drag axis
  89831. rotationMesh.scaling.scaleInPlace(0.1);
  89832. rotationMesh.material = coloredMaterial;
  89833. rotationMesh.rotation.x = Math.PI / 2;
  89834. parentMesh.addChild(rotationMesh);
  89835. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89836. _this._rootMesh.addChild(parentMesh);
  89837. // Add drag behavior to handle events when the gizmo is dragged
  89838. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89839. _this.dragBehavior.moveAttached = false;
  89840. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  89841. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  89842. _this._rootMesh.addBehavior(_this.dragBehavior);
  89843. var lastDragPosition = new BABYLON.Vector3();
  89844. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89845. if (_this.attachedMesh) {
  89846. lastDragPosition.copyFrom(e.dragPlanePoint);
  89847. }
  89848. });
  89849. var rotationMatrix = new BABYLON.Matrix();
  89850. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89851. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89852. var tmpSnapEvent = { snapDistance: 0 };
  89853. var currentSnapDragDistance = 0;
  89854. _this.dragBehavior.onDragObservable.add(function (event) {
  89855. if (_this.attachedMesh) {
  89856. if (!_this.attachedMesh.rotationQuaternion) {
  89857. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89858. }
  89859. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89860. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89861. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89862. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89863. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89864. var angle = Math.atan2(cross.length(), dot);
  89865. planeNormalTowardsCamera.copyFrom(planeNormal);
  89866. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89867. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89868. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89869. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89870. }
  89871. // Flip up vector depending on which side the camera is on
  89872. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89873. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89874. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89875. planeNormalTowardsCamera.scaleInPlace(-1);
  89876. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89877. }
  89878. }
  89879. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89880. if (halfCircleSide)
  89881. angle = -angle;
  89882. // Snapping logic
  89883. var snapped = false;
  89884. if (_this.snapDistance != 0) {
  89885. currentSnapDragDistance += angle;
  89886. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89887. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89888. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89889. angle = _this.snapDistance * dragSteps;
  89890. snapped = true;
  89891. }
  89892. else {
  89893. angle = 0;
  89894. }
  89895. }
  89896. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89897. var quaternionCoefficient = Math.sin(angle / 2);
  89898. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89899. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89900. // Rotate selected mesh quaternion over fixed axis
  89901. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89902. }
  89903. else {
  89904. // Rotate selected mesh quaternion over rotated axis
  89905. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  89906. }
  89907. lastDragPosition.copyFrom(event.dragPlanePoint);
  89908. if (snapped) {
  89909. tmpSnapEvent.snapDistance = angle;
  89910. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89911. }
  89912. }
  89913. });
  89914. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89915. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89916. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89917. m.material = hoverMaterial;
  89918. });
  89919. }
  89920. else {
  89921. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89922. m.material = coloredMaterial;
  89923. });
  89924. }
  89925. });
  89926. return _this;
  89927. }
  89928. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89929. if (this.dragBehavior) {
  89930. this.dragBehavior.enabled = value ? true : false;
  89931. }
  89932. };
  89933. /**
  89934. * Disposes of the gizmo
  89935. */
  89936. PlaneRotationGizmo.prototype.dispose = function () {
  89937. this.onSnapObservable.clear();
  89938. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89939. this.dragBehavior.detach();
  89940. _super.prototype.dispose.call(this);
  89941. };
  89942. return PlaneRotationGizmo;
  89943. }(BABYLON.Gizmo));
  89944. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89945. })(BABYLON || (BABYLON = {}));
  89946. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89947. var BABYLON;
  89948. (function (BABYLON) {
  89949. /**
  89950. * Gizmo that enables dragging a mesh along 3 axis
  89951. */
  89952. var PositionGizmo = /** @class */ (function (_super) {
  89953. __extends(PositionGizmo, _super);
  89954. /**
  89955. * Creates a PositionGizmo
  89956. * @param gizmoLayer The utility layer the gizmo will be added to
  89957. */
  89958. function PositionGizmo(gizmoLayer) {
  89959. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89960. var _this = _super.call(this, gizmoLayer) || this;
  89961. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89962. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89963. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89964. _this.attachedMesh = null;
  89965. return _this;
  89966. }
  89967. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89968. set: function (mesh) {
  89969. if (this.xGizmo) {
  89970. this.xGizmo.attachedMesh = mesh;
  89971. this.yGizmo.attachedMesh = mesh;
  89972. this.zGizmo.attachedMesh = mesh;
  89973. }
  89974. },
  89975. enumerable: true,
  89976. configurable: true
  89977. });
  89978. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89979. get: function () {
  89980. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89981. },
  89982. set: function (value) {
  89983. if (this.xGizmo) {
  89984. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89985. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89986. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89987. }
  89988. },
  89989. enumerable: true,
  89990. configurable: true
  89991. });
  89992. /**
  89993. * Disposes of the gizmo
  89994. */
  89995. PositionGizmo.prototype.dispose = function () {
  89996. this.xGizmo.dispose();
  89997. this.yGizmo.dispose();
  89998. this.zGizmo.dispose();
  89999. };
  90000. return PositionGizmo;
  90001. }(BABYLON.Gizmo));
  90002. BABYLON.PositionGizmo = PositionGizmo;
  90003. })(BABYLON || (BABYLON = {}));
  90004. //# sourceMappingURL=babylon.positionGizmo.js.map
  90005. var BABYLON;
  90006. (function (BABYLON) {
  90007. /**
  90008. * Gizmo that enables rotating a mesh along 3 axis
  90009. */
  90010. var RotationGizmo = /** @class */ (function (_super) {
  90011. __extends(RotationGizmo, _super);
  90012. /**
  90013. * Creates a RotationGizmo
  90014. * @param gizmoLayer The utility layer the gizmo will be added to
  90015. */
  90016. function RotationGizmo(gizmoLayer) {
  90017. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90018. var _this = _super.call(this, gizmoLayer) || this;
  90019. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90020. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90021. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90022. _this.attachedMesh = null;
  90023. return _this;
  90024. }
  90025. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  90026. set: function (mesh) {
  90027. if (this.xGizmo) {
  90028. this.xGizmo.attachedMesh = mesh;
  90029. this.yGizmo.attachedMesh = mesh;
  90030. this.zGizmo.attachedMesh = mesh;
  90031. }
  90032. },
  90033. enumerable: true,
  90034. configurable: true
  90035. });
  90036. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90037. get: function () {
  90038. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90039. },
  90040. set: function (value) {
  90041. if (this.xGizmo) {
  90042. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90043. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90044. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90045. }
  90046. },
  90047. enumerable: true,
  90048. configurable: true
  90049. });
  90050. /**
  90051. * Disposes of the gizmo
  90052. */
  90053. RotationGizmo.prototype.dispose = function () {
  90054. this.xGizmo.dispose();
  90055. this.yGizmo.dispose();
  90056. this.zGizmo.dispose();
  90057. };
  90058. return RotationGizmo;
  90059. }(BABYLON.Gizmo));
  90060. BABYLON.RotationGizmo = RotationGizmo;
  90061. })(BABYLON || (BABYLON = {}));
  90062. //# sourceMappingURL=babylon.rotationGizmo.js.map
  90063. var BABYLON;
  90064. (function (BABYLON) {
  90065. /**
  90066. * Gizmo that enables scaling a mesh along 3 axis
  90067. */
  90068. var ScaleGizmo = /** @class */ (function (_super) {
  90069. __extends(ScaleGizmo, _super);
  90070. /**
  90071. * Creates a ScaleGizmo
  90072. * @param gizmoLayer The utility layer the gizmo will be added to
  90073. */
  90074. function ScaleGizmo(gizmoLayer) {
  90075. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90076. var _this = _super.call(this, gizmoLayer) || this;
  90077. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  90078. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  90079. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  90080. _this.attachedMesh = null;
  90081. return _this;
  90082. }
  90083. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  90084. set: function (mesh) {
  90085. if (this.xGizmo) {
  90086. this.xGizmo.attachedMesh = mesh;
  90087. this.yGizmo.attachedMesh = mesh;
  90088. this.zGizmo.attachedMesh = mesh;
  90089. }
  90090. },
  90091. enumerable: true,
  90092. configurable: true
  90093. });
  90094. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  90095. get: function () {
  90096. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  90097. },
  90098. set: function (value) {
  90099. if (this.xGizmo) {
  90100. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90101. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90102. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  90103. }
  90104. },
  90105. enumerable: true,
  90106. configurable: true
  90107. });
  90108. /**
  90109. * Disposes of the gizmo
  90110. */
  90111. ScaleGizmo.prototype.dispose = function () {
  90112. this.xGizmo.dispose();
  90113. this.yGizmo.dispose();
  90114. this.zGizmo.dispose();
  90115. };
  90116. return ScaleGizmo;
  90117. }(BABYLON.Gizmo));
  90118. BABYLON.ScaleGizmo = ScaleGizmo;
  90119. })(BABYLON || (BABYLON = {}));
  90120. //# sourceMappingURL=babylon.scaleGizmo.js.map
  90121. var BABYLON;
  90122. (function (BABYLON) {
  90123. /**
  90124. * Bounding box gizmo
  90125. */
  90126. var BoundingBoxGizmo = /** @class */ (function (_super) {
  90127. __extends(BoundingBoxGizmo, _super);
  90128. /**
  90129. * Creates an BoundingBoxGizmo
  90130. * @param gizmoLayer The utility layer the gizmo will be added to
  90131. * @param color The color of the gizmo
  90132. */
  90133. function BoundingBoxGizmo(color, gizmoLayer) {
  90134. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  90135. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  90136. var _this = _super.call(this, gizmoLayer) || this;
  90137. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  90138. _this._renderObserver = null;
  90139. _this._pointerObserver = null;
  90140. _this._scaleDragSpeed = 0.2;
  90141. _this._tmpQuaternion = new BABYLON.Quaternion();
  90142. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90143. /**
  90144. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  90145. */
  90146. _this.rotationSphereSize = 0.1;
  90147. /**
  90148. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  90149. */
  90150. _this.scaleBoxSize = 0.1;
  90151. /**
  90152. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  90153. */
  90154. _this.fixedDragMeshScreenSize = false;
  90155. /**
  90156. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  90157. */
  90158. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  90159. /**
  90160. * Fired when a rotation sphere or scale box is dragged
  90161. */
  90162. _this.onDragStartObservable = new BABYLON.Observable();
  90163. /**
  90164. * Fired when a rotation sphere or scale box drag is started
  90165. */
  90166. _this.onDragObservable = new BABYLON.Observable();
  90167. /**
  90168. * Fired when a rotation sphere or scale box drag is needed
  90169. */
  90170. _this.onDragEndObservable = new BABYLON.Observable();
  90171. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  90172. _this._updateScale = false;
  90173. // Create Materials
  90174. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90175. coloredMaterial.disableLighting = true;
  90176. coloredMaterial.emissiveColor = color;
  90177. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  90178. hoverColoredMaterial.disableLighting = true;
  90179. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  90180. // Build bounding box out of lines
  90181. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90182. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  90183. var lines = [];
  90184. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  90185. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90186. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90187. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90188. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90189. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90190. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90191. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90192. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90193. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90194. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  90195. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  90196. lines.forEach(function (l) {
  90197. l.color = color;
  90198. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  90199. l.isPickable = false;
  90200. _this._lineBoundingBox.addChild(l);
  90201. });
  90202. _this._rootMesh.addChild(_this._lineBoundingBox);
  90203. // Create rotation spheres
  90204. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90205. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  90206. var _loop_1 = function (i_1) {
  90207. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  90208. sphere.rotationQuaternion = new BABYLON.Quaternion();
  90209. sphere.material = coloredMaterial;
  90210. // Drag behavior
  90211. _dragBehavior = new BABYLON.PointerDragBehavior({});
  90212. _dragBehavior.moveAttached = false;
  90213. _dragBehavior.updateDragPlane = false;
  90214. sphere.addBehavior(_dragBehavior);
  90215. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  90216. var totalTurnAmountOfDrag = 0;
  90217. _dragBehavior.onDragStartObservable.add(function (event) {
  90218. startingTurnDirection.copyFrom(sphere.forward);
  90219. totalTurnAmountOfDrag = 0;
  90220. });
  90221. _dragBehavior.onDragObservable.add(function (event) {
  90222. _this.onDragObservable.notifyObservers({});
  90223. if (_this.attachedMesh) {
  90224. var worldDragDirection = startingTurnDirection;
  90225. // Project the world right on to the drag plane
  90226. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  90227. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  90228. // project drag delta on to the resulting drag axis and rotate based on that
  90229. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  90230. // Rotate based on axis
  90231. if (!_this.attachedMesh.rotationQuaternion) {
  90232. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  90233. }
  90234. // Do not allow the object to turn more than a full circle
  90235. totalTurnAmountOfDrag += projectDist;
  90236. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  90237. if (i_1 >= 8) {
  90238. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  90239. }
  90240. else if (i_1 >= 4) {
  90241. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  90242. }
  90243. else {
  90244. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  90245. }
  90246. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  90247. }
  90248. }
  90249. });
  90250. // Selection/deselection
  90251. _dragBehavior.onDragStartObservable.add(function () {
  90252. _this.onDragStartObservable.notifyObservers({});
  90253. _this._selectNode(sphere);
  90254. });
  90255. _dragBehavior.onDragEndObservable.add(function () {
  90256. _this.onDragEndObservable.notifyObservers({});
  90257. _this._selectNode(null);
  90258. });
  90259. this_1._rotateSpheresParent.addChild(sphere);
  90260. };
  90261. var this_1 = this, _dragBehavior;
  90262. for (var i_1 = 0; i_1 < 12; i_1++) {
  90263. _loop_1(i_1);
  90264. }
  90265. _this._rootMesh.addChild(_this._rotateSpheresParent);
  90266. // Create scale cubes
  90267. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  90268. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  90269. for (var i = 0; i < 2; i++) {
  90270. for (var j = 0; j < 2; j++) {
  90271. var _loop_2 = function () {
  90272. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  90273. box.material = coloredMaterial;
  90274. // Dragging logic
  90275. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  90276. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  90277. _dragBehavior.moveAttached = false;
  90278. box.addBehavior(_dragBehavior);
  90279. _dragBehavior.onDragObservable.add(function (event) {
  90280. _this.onDragObservable.notifyObservers({});
  90281. if (_this.attachedMesh) {
  90282. // Current boudning box dimensions
  90283. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  90284. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  90285. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  90286. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  90287. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  90288. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  90289. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  90290. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  90291. // Update scale and position
  90292. _this.attachedMesh.scaling.addInPlace(deltaScale);
  90293. if (_this.attachedMesh.scaling.x < 0 || _this.attachedMesh.scaling.y < 0 || _this.attachedMesh.scaling.z < 0) {
  90294. _this.attachedMesh.scaling.subtractInPlace(deltaScale);
  90295. }
  90296. else {
  90297. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  90298. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  90299. }
  90300. }
  90301. });
  90302. // Selection/deselection
  90303. _dragBehavior.onDragStartObservable.add(function () {
  90304. _this.onDragStartObservable.notifyObservers({});
  90305. _this._selectNode(box);
  90306. });
  90307. _dragBehavior.onDragEndObservable.add(function () {
  90308. _this.onDragEndObservable.notifyObservers({});
  90309. _this._selectNode(null);
  90310. });
  90311. this_2._scaleBoxesParent.addChild(box);
  90312. };
  90313. var this_2 = this, _dragBehavior;
  90314. for (var k = 0; k < 2; k++) {
  90315. _loop_2();
  90316. }
  90317. }
  90318. }
  90319. _this._rootMesh.addChild(_this._scaleBoxesParent);
  90320. // Hover color change
  90321. var pointerIds = new Array();
  90322. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  90323. if (!pointerIds[pointerInfo.event.pointerId]) {
  90324. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  90325. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  90326. pointerIds[pointerInfo.event.pointerId] = mesh;
  90327. mesh.material = hoverColoredMaterial;
  90328. }
  90329. });
  90330. }
  90331. else {
  90332. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  90333. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  90334. delete pointerIds[pointerInfo.event.pointerId];
  90335. }
  90336. }
  90337. });
  90338. // Update bounding box positions
  90339. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  90340. _this._updateBoundingBox();
  90341. });
  90342. _this._updateBoundingBox();
  90343. return _this;
  90344. }
  90345. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  90346. this._rotateSpheresParent.getChildMeshes()
  90347. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  90348. m.isVisible = (!selectedMesh || m == selectedMesh);
  90349. });
  90350. };
  90351. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  90352. if (this.attachedMesh) {
  90353. // Update bounding dimensions/positions
  90354. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  90355. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  90356. this._boundingDimensions.copyFrom(boundBoxDimensions);
  90357. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  90358. }
  90359. // Update rotation sphere locations
  90360. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  90361. for (var i = 0; i < 3; i++) {
  90362. for (var j = 0; j < 2; j++) {
  90363. for (var k = 0; k < 2; k++) {
  90364. var index = ((i * 4) + (j * 2)) + k;
  90365. if (i == 0) {
  90366. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90367. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90368. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90369. }
  90370. if (i == 1) {
  90371. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  90372. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90373. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90374. }
  90375. if (i == 2) {
  90376. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  90377. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90378. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  90379. }
  90380. if (this.fixedDragMeshScreenSize) {
  90381. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90382. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90383. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90384. }
  90385. else {
  90386. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  90387. }
  90388. }
  90389. }
  90390. }
  90391. // Update scale box locations
  90392. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  90393. for (var i = 0; i < 2; i++) {
  90394. for (var j = 0; j < 2; j++) {
  90395. for (var k = 0; k < 2; k++) {
  90396. var index = ((i * 4) + (j * 2)) + k;
  90397. if (scaleBoxes[index]) {
  90398. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90399. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90400. if (this.fixedDragMeshScreenSize) {
  90401. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90402. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90403. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90404. }
  90405. else {
  90406. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90407. }
  90408. }
  90409. }
  90410. }
  90411. }
  90412. };
  90413. /**
  90414. * Enables rotation on the specified axis and disables rotation on the others
  90415. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90416. */
  90417. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90418. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90419. if (i < 4) {
  90420. m.setEnabled(axis.indexOf("x") != -1);
  90421. }
  90422. else if (i < 8) {
  90423. m.setEnabled(axis.indexOf("y") != -1);
  90424. }
  90425. else {
  90426. m.setEnabled(axis.indexOf("z") != -1);
  90427. }
  90428. });
  90429. };
  90430. /**
  90431. * Disposes of the gizmo
  90432. */
  90433. BoundingBoxGizmo.prototype.dispose = function () {
  90434. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90435. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90436. this._lineBoundingBox.dispose();
  90437. this._rotateSpheresParent.dispose();
  90438. this._scaleBoxesParent.dispose();
  90439. _super.prototype.dispose.call(this);
  90440. };
  90441. return BoundingBoxGizmo;
  90442. }(BABYLON.Gizmo));
  90443. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90444. })(BABYLON || (BABYLON = {}));
  90445. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90446. var BABYLON;
  90447. (function (BABYLON) {
  90448. /**
  90449. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90450. */
  90451. var GizmoManager = /** @class */ (function () {
  90452. /**
  90453. * Instatiates a gizmo manager
  90454. * @param scene the scene to overlay the gizmos on top of
  90455. * @param options If only a single gizmo should exist at one time
  90456. */
  90457. function GizmoManager(scene, options) {
  90458. var _this = this;
  90459. this.scene = scene;
  90460. // Set of gizmos that are currently in the scene for each mesh
  90461. this._gizmoSet = {};
  90462. this._pointerObserver = null;
  90463. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  90464. // Options parsing
  90465. if (!options) {
  90466. options = {};
  90467. }
  90468. if (options.singleGizmo === undefined) {
  90469. options.singleGizmo = true;
  90470. }
  90471. // Instatiate/dispose gizmos based on pointer actions
  90472. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90473. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90474. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90475. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  90476. if (options.singleGizmo) {
  90477. _this._clearGizmos();
  90478. }
  90479. // Enable gizmo when mesh is selected
  90480. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  90481. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90482. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90483. }
  90484. else {
  90485. if (!options.singleGizmo) {
  90486. // Disable gizmo when clicked again
  90487. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  90488. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  90489. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  90490. }
  90491. }
  90492. }
  90493. else {
  90494. if (options.singleGizmo) {
  90495. // Disable gizmo when clicked away
  90496. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90497. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  90498. if (gizmoPick && !gizmoPick.hit) {
  90499. _this._clearGizmos();
  90500. }
  90501. }
  90502. }
  90503. }
  90504. }
  90505. });
  90506. }
  90507. /**
  90508. * Disposes of the gizmo manager
  90509. */
  90510. GizmoManager.prototype.dispose = function () {
  90511. this.scene.onPointerObservable.remove(this._pointerObserver);
  90512. this._clearGizmos();
  90513. this._gizmoLayer.dispose();
  90514. };
  90515. GizmoManager.prototype._clearGizmos = function () {
  90516. for (var key in this._gizmoSet) {
  90517. if (this._gizmoSet.hasOwnProperty(key)) {
  90518. this._gizmoSet[key].positionGizmo.dispose();
  90519. this._gizmoSet[key].rotationGizmo.dispose();
  90520. delete this._gizmoSet[key];
  90521. }
  90522. }
  90523. };
  90524. return GizmoManager;
  90525. }());
  90526. BABYLON.GizmoManager = GizmoManager;
  90527. })(BABYLON || (BABYLON = {}));
  90528. //# sourceMappingURL=babylon.gizmoManager.js.map
  90529. var BABYLON;
  90530. (function (BABYLON) {
  90531. /**
  90532. * Defines a target to use with MorphTargetManager
  90533. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90534. */
  90535. var MorphTarget = /** @class */ (function () {
  90536. /**
  90537. * Creates a new MorphTarget
  90538. * @param name defines the name of the target
  90539. * @param influence defines the influence to use
  90540. */
  90541. function MorphTarget(
  90542. /** defines the name of the target */
  90543. name, influence, scene) {
  90544. if (influence === void 0) { influence = 0; }
  90545. if (scene === void 0) { scene = null; }
  90546. this.name = name;
  90547. /**
  90548. * Gets or sets the list of animations
  90549. */
  90550. this.animations = new Array();
  90551. this._positions = null;
  90552. this._normals = null;
  90553. this._tangents = null;
  90554. /**
  90555. * Observable raised when the influence changes
  90556. */
  90557. this.onInfluenceChanged = new BABYLON.Observable();
  90558. this._animationPropertiesOverride = null;
  90559. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90560. this.influence = influence;
  90561. }
  90562. Object.defineProperty(MorphTarget.prototype, "influence", {
  90563. /**
  90564. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90565. */
  90566. get: function () {
  90567. return this._influence;
  90568. },
  90569. set: function (influence) {
  90570. if (this._influence === influence) {
  90571. return;
  90572. }
  90573. var previous = this._influence;
  90574. this._influence = influence;
  90575. if (this.onInfluenceChanged.hasObservers) {
  90576. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90577. }
  90578. },
  90579. enumerable: true,
  90580. configurable: true
  90581. });
  90582. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90583. /**
  90584. * Gets or sets the animation properties override
  90585. */
  90586. get: function () {
  90587. if (!this._animationPropertiesOverride && this._scene) {
  90588. return this._scene.animationPropertiesOverride;
  90589. }
  90590. return this._animationPropertiesOverride;
  90591. },
  90592. set: function (value) {
  90593. this._animationPropertiesOverride = value;
  90594. },
  90595. enumerable: true,
  90596. configurable: true
  90597. });
  90598. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90599. /**
  90600. * Gets a boolean defining if the target contains position data
  90601. */
  90602. get: function () {
  90603. return !!this._positions;
  90604. },
  90605. enumerable: true,
  90606. configurable: true
  90607. });
  90608. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90609. /**
  90610. * Gets a boolean defining if the target contains normal data
  90611. */
  90612. get: function () {
  90613. return !!this._normals;
  90614. },
  90615. enumerable: true,
  90616. configurable: true
  90617. });
  90618. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90619. /**
  90620. * Gets a boolean defining if the target contains tangent data
  90621. */
  90622. get: function () {
  90623. return !!this._tangents;
  90624. },
  90625. enumerable: true,
  90626. configurable: true
  90627. });
  90628. /**
  90629. * Affects position data to this target
  90630. * @param data defines the position data to use
  90631. */
  90632. MorphTarget.prototype.setPositions = function (data) {
  90633. this._positions = data;
  90634. };
  90635. /**
  90636. * Gets the position data stored in this target
  90637. * @returns a FloatArray containing the position data (or null if not present)
  90638. */
  90639. MorphTarget.prototype.getPositions = function () {
  90640. return this._positions;
  90641. };
  90642. /**
  90643. * Affects normal data to this target
  90644. * @param data defines the normal data to use
  90645. */
  90646. MorphTarget.prototype.setNormals = function (data) {
  90647. this._normals = data;
  90648. };
  90649. /**
  90650. * Gets the normal data stored in this target
  90651. * @returns a FloatArray containing the normal data (or null if not present)
  90652. */
  90653. MorphTarget.prototype.getNormals = function () {
  90654. return this._normals;
  90655. };
  90656. /**
  90657. * Affects tangent data to this target
  90658. * @param data defines the tangent data to use
  90659. */
  90660. MorphTarget.prototype.setTangents = function (data) {
  90661. this._tangents = data;
  90662. };
  90663. /**
  90664. * Gets the tangent data stored in this target
  90665. * @returns a FloatArray containing the tangent data (or null if not present)
  90666. */
  90667. MorphTarget.prototype.getTangents = function () {
  90668. return this._tangents;
  90669. };
  90670. /**
  90671. * Serializes the current target into a Serialization object
  90672. * @returns the serialized object
  90673. */
  90674. MorphTarget.prototype.serialize = function () {
  90675. var serializationObject = {};
  90676. serializationObject.name = this.name;
  90677. serializationObject.influence = this.influence;
  90678. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90679. if (this.hasNormals) {
  90680. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90681. }
  90682. if (this.hasTangents) {
  90683. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90684. }
  90685. // Animations
  90686. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90687. return serializationObject;
  90688. };
  90689. // Statics
  90690. /**
  90691. * Creates a new target from serialized data
  90692. * @param serializationObject defines the serialized data to use
  90693. * @returns a new MorphTarget
  90694. */
  90695. MorphTarget.Parse = function (serializationObject) {
  90696. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90697. result.setPositions(serializationObject.positions);
  90698. if (serializationObject.normals) {
  90699. result.setNormals(serializationObject.normals);
  90700. }
  90701. if (serializationObject.tangents) {
  90702. result.setTangents(serializationObject.tangents);
  90703. }
  90704. // Animations
  90705. if (serializationObject.animations) {
  90706. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90707. var parsedAnimation = serializationObject.animations[animationIndex];
  90708. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90709. }
  90710. }
  90711. return result;
  90712. };
  90713. /**
  90714. * Creates a MorphTarget from mesh data
  90715. * @param mesh defines the source mesh
  90716. * @param name defines the name to use for the new target
  90717. * @param influence defines the influence to attach to the target
  90718. * @returns a new MorphTarget
  90719. */
  90720. MorphTarget.FromMesh = function (mesh, name, influence) {
  90721. if (!name) {
  90722. name = mesh.name;
  90723. }
  90724. var result = new MorphTarget(name, influence, mesh.getScene());
  90725. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90726. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90727. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90728. }
  90729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90730. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90731. }
  90732. return result;
  90733. };
  90734. return MorphTarget;
  90735. }());
  90736. BABYLON.MorphTarget = MorphTarget;
  90737. })(BABYLON || (BABYLON = {}));
  90738. //# sourceMappingURL=babylon.morphTarget.js.map
  90739. var BABYLON;
  90740. (function (BABYLON) {
  90741. /**
  90742. * This class is used to deform meshes using morphing between different targets
  90743. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90744. */
  90745. var MorphTargetManager = /** @class */ (function () {
  90746. /**
  90747. * Creates a new MorphTargetManager
  90748. * @param scene defines the current scene
  90749. */
  90750. function MorphTargetManager(scene) {
  90751. if (scene === void 0) { scene = null; }
  90752. this._targets = new Array();
  90753. this._targetObservable = new Array();
  90754. this._activeTargets = new BABYLON.SmartArray(16);
  90755. this._supportsNormals = false;
  90756. this._supportsTangents = false;
  90757. this._vertexCount = 0;
  90758. this._uniqueId = 0;
  90759. this._tempInfluences = new Array();
  90760. if (!scene) {
  90761. scene = BABYLON.Engine.LastCreatedScene;
  90762. }
  90763. this._scene = scene;
  90764. if (this._scene) {
  90765. this._scene.morphTargetManagers.push(this);
  90766. this._uniqueId = this._scene.getUniqueId();
  90767. }
  90768. }
  90769. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90770. /**
  90771. * Gets the unique ID of this manager
  90772. */
  90773. get: function () {
  90774. return this._uniqueId;
  90775. },
  90776. enumerable: true,
  90777. configurable: true
  90778. });
  90779. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90780. /**
  90781. * Gets the number of vertices handled by this manager
  90782. */
  90783. get: function () {
  90784. return this._vertexCount;
  90785. },
  90786. enumerable: true,
  90787. configurable: true
  90788. });
  90789. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90790. /**
  90791. * Gets a boolean indicating if this manager supports morphing of normals
  90792. */
  90793. get: function () {
  90794. return this._supportsNormals;
  90795. },
  90796. enumerable: true,
  90797. configurable: true
  90798. });
  90799. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90800. /**
  90801. * Gets a boolean indicating if this manager supports morphing of tangents
  90802. */
  90803. get: function () {
  90804. return this._supportsTangents;
  90805. },
  90806. enumerable: true,
  90807. configurable: true
  90808. });
  90809. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90810. /**
  90811. * Gets the number of targets stored in this manager
  90812. */
  90813. get: function () {
  90814. return this._targets.length;
  90815. },
  90816. enumerable: true,
  90817. configurable: true
  90818. });
  90819. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90820. /**
  90821. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90822. */
  90823. get: function () {
  90824. return this._activeTargets.length;
  90825. },
  90826. enumerable: true,
  90827. configurable: true
  90828. });
  90829. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90830. /**
  90831. * Gets the list of influences (one per target)
  90832. */
  90833. get: function () {
  90834. return this._influences;
  90835. },
  90836. enumerable: true,
  90837. configurable: true
  90838. });
  90839. /**
  90840. * Gets the active target at specified index. An active target is a target with an influence > 0
  90841. * @param index defines the index to check
  90842. * @returns the requested target
  90843. */
  90844. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90845. return this._activeTargets.data[index];
  90846. };
  90847. /**
  90848. * Gets the target at specified index
  90849. * @param index defines the index to check
  90850. * @returns the requested target
  90851. */
  90852. MorphTargetManager.prototype.getTarget = function (index) {
  90853. return this._targets[index];
  90854. };
  90855. /**
  90856. * Add a new target to this manager
  90857. * @param target defines the target to add
  90858. */
  90859. MorphTargetManager.prototype.addTarget = function (target) {
  90860. var _this = this;
  90861. this._targets.push(target);
  90862. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90863. _this._syncActiveTargets(needUpdate);
  90864. }));
  90865. this._syncActiveTargets(true);
  90866. };
  90867. /**
  90868. * Removes a target from the manager
  90869. * @param target defines the target to remove
  90870. */
  90871. MorphTargetManager.prototype.removeTarget = function (target) {
  90872. var index = this._targets.indexOf(target);
  90873. if (index >= 0) {
  90874. this._targets.splice(index, 1);
  90875. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90876. this._syncActiveTargets(true);
  90877. }
  90878. };
  90879. /**
  90880. * Serializes the current manager into a Serialization object
  90881. * @returns the serialized object
  90882. */
  90883. MorphTargetManager.prototype.serialize = function () {
  90884. var serializationObject = {};
  90885. serializationObject.id = this.uniqueId;
  90886. serializationObject.targets = [];
  90887. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90888. var target = _a[_i];
  90889. serializationObject.targets.push(target.serialize());
  90890. }
  90891. return serializationObject;
  90892. };
  90893. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90894. var influenceCount = 0;
  90895. this._activeTargets.reset();
  90896. this._supportsNormals = true;
  90897. this._supportsTangents = true;
  90898. this._vertexCount = 0;
  90899. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90900. var target = _a[_i];
  90901. this._activeTargets.push(target);
  90902. this._tempInfluences[influenceCount++] = target.influence;
  90903. var positions = target.getPositions();
  90904. if (positions) {
  90905. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90906. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90907. var vertexCount = positions.length / 3;
  90908. if (this._vertexCount === 0) {
  90909. this._vertexCount = vertexCount;
  90910. }
  90911. else if (this._vertexCount !== vertexCount) {
  90912. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90913. return;
  90914. }
  90915. }
  90916. }
  90917. if (!this._influences || this._influences.length !== influenceCount) {
  90918. this._influences = new Float32Array(influenceCount);
  90919. }
  90920. for (var index = 0; index < influenceCount; index++) {
  90921. this._influences[index] = this._tempInfluences[index];
  90922. }
  90923. if (needUpdate) {
  90924. this.synchronize();
  90925. }
  90926. };
  90927. /**
  90928. * Syncrhonize the targets with all the meshes using this morph target manager
  90929. */
  90930. MorphTargetManager.prototype.synchronize = function () {
  90931. if (!this._scene) {
  90932. return;
  90933. }
  90934. // Flag meshes as dirty to resync with the active targets
  90935. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90936. var mesh = _a[_i];
  90937. if (mesh.morphTargetManager === this) {
  90938. mesh._syncGeometryWithMorphTargetManager();
  90939. }
  90940. }
  90941. };
  90942. // Statics
  90943. /**
  90944. * Creates a new MorphTargetManager from serialized data
  90945. * @param serializationObject defines the serialized data
  90946. * @param scene defines the hosting scene
  90947. * @returns the new MorphTargetManager
  90948. */
  90949. MorphTargetManager.Parse = function (serializationObject, scene) {
  90950. var result = new MorphTargetManager(scene);
  90951. result._uniqueId = serializationObject.id;
  90952. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90953. var targetData = _a[_i];
  90954. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90955. }
  90956. return result;
  90957. };
  90958. return MorphTargetManager;
  90959. }());
  90960. BABYLON.MorphTargetManager = MorphTargetManager;
  90961. })(BABYLON || (BABYLON = {}));
  90962. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90963. var BABYLON;
  90964. (function (BABYLON) {
  90965. var Octree = /** @class */ (function () {
  90966. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90967. if (maxDepth === void 0) { maxDepth = 2; }
  90968. this.maxDepth = maxDepth;
  90969. this.dynamicContent = new Array();
  90970. this._maxBlockCapacity = maxBlockCapacity || 64;
  90971. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90972. this._creationFunc = creationFunc;
  90973. }
  90974. // Methods
  90975. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90976. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90977. };
  90978. Octree.prototype.addMesh = function (entry) {
  90979. for (var index = 0; index < this.blocks.length; index++) {
  90980. var block = this.blocks[index];
  90981. block.addEntry(entry);
  90982. }
  90983. };
  90984. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90985. this._selectionContent.reset();
  90986. for (var index = 0; index < this.blocks.length; index++) {
  90987. var block = this.blocks[index];
  90988. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90989. }
  90990. if (allowDuplicate) {
  90991. this._selectionContent.concat(this.dynamicContent);
  90992. }
  90993. else {
  90994. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90995. }
  90996. return this._selectionContent;
  90997. };
  90998. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90999. this._selectionContent.reset();
  91000. for (var index = 0; index < this.blocks.length; index++) {
  91001. var block = this.blocks[index];
  91002. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  91003. }
  91004. if (allowDuplicate) {
  91005. this._selectionContent.concat(this.dynamicContent);
  91006. }
  91007. else {
  91008. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91009. }
  91010. return this._selectionContent;
  91011. };
  91012. Octree.prototype.intersectsRay = function (ray) {
  91013. this._selectionContent.reset();
  91014. for (var index = 0; index < this.blocks.length; index++) {
  91015. var block = this.blocks[index];
  91016. block.intersectsRay(ray, this._selectionContent);
  91017. }
  91018. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  91019. return this._selectionContent;
  91020. };
  91021. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  91022. target.blocks = new Array();
  91023. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  91024. // Segmenting space
  91025. for (var x = 0; x < 2; x++) {
  91026. for (var y = 0; y < 2; y++) {
  91027. for (var z = 0; z < 2; z++) {
  91028. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  91029. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  91030. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  91031. block.addEntries(entries);
  91032. target.blocks.push(block);
  91033. }
  91034. }
  91035. }
  91036. };
  91037. Octree.CreationFuncForMeshes = function (entry, block) {
  91038. var boundingInfo = entry.getBoundingInfo();
  91039. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91040. block.entries.push(entry);
  91041. }
  91042. };
  91043. Octree.CreationFuncForSubMeshes = function (entry, block) {
  91044. var boundingInfo = entry.getBoundingInfo();
  91045. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  91046. block.entries.push(entry);
  91047. }
  91048. };
  91049. return Octree;
  91050. }());
  91051. BABYLON.Octree = Octree;
  91052. })(BABYLON || (BABYLON = {}));
  91053. //# sourceMappingURL=babylon.octree.js.map
  91054. var BABYLON;
  91055. (function (BABYLON) {
  91056. var OctreeBlock = /** @class */ (function () {
  91057. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  91058. this.entries = new Array();
  91059. this._boundingVectors = new Array();
  91060. this._capacity = capacity;
  91061. this._depth = depth;
  91062. this._maxDepth = maxDepth;
  91063. this._creationFunc = creationFunc;
  91064. this._minPoint = minPoint;
  91065. this._maxPoint = maxPoint;
  91066. this._boundingVectors.push(minPoint.clone());
  91067. this._boundingVectors.push(maxPoint.clone());
  91068. this._boundingVectors.push(minPoint.clone());
  91069. this._boundingVectors[2].x = maxPoint.x;
  91070. this._boundingVectors.push(minPoint.clone());
  91071. this._boundingVectors[3].y = maxPoint.y;
  91072. this._boundingVectors.push(minPoint.clone());
  91073. this._boundingVectors[4].z = maxPoint.z;
  91074. this._boundingVectors.push(maxPoint.clone());
  91075. this._boundingVectors[5].z = minPoint.z;
  91076. this._boundingVectors.push(maxPoint.clone());
  91077. this._boundingVectors[6].x = minPoint.x;
  91078. this._boundingVectors.push(maxPoint.clone());
  91079. this._boundingVectors[7].y = minPoint.y;
  91080. }
  91081. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  91082. // Property
  91083. get: function () {
  91084. return this._capacity;
  91085. },
  91086. enumerable: true,
  91087. configurable: true
  91088. });
  91089. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  91090. get: function () {
  91091. return this._minPoint;
  91092. },
  91093. enumerable: true,
  91094. configurable: true
  91095. });
  91096. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  91097. get: function () {
  91098. return this._maxPoint;
  91099. },
  91100. enumerable: true,
  91101. configurable: true
  91102. });
  91103. // Methods
  91104. OctreeBlock.prototype.addEntry = function (entry) {
  91105. if (this.blocks) {
  91106. for (var index = 0; index < this.blocks.length; index++) {
  91107. var block = this.blocks[index];
  91108. block.addEntry(entry);
  91109. }
  91110. return;
  91111. }
  91112. this._creationFunc(entry, this);
  91113. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  91114. this.createInnerBlocks();
  91115. }
  91116. };
  91117. OctreeBlock.prototype.addEntries = function (entries) {
  91118. for (var index = 0; index < entries.length; index++) {
  91119. var mesh = entries[index];
  91120. this.addEntry(mesh);
  91121. }
  91122. };
  91123. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  91124. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  91125. if (this.blocks) {
  91126. for (var index = 0; index < this.blocks.length; index++) {
  91127. var block = this.blocks[index];
  91128. block.select(frustumPlanes, selection, allowDuplicate);
  91129. }
  91130. return;
  91131. }
  91132. if (allowDuplicate) {
  91133. selection.concat(this.entries);
  91134. }
  91135. else {
  91136. selection.concatWithNoDuplicate(this.entries);
  91137. }
  91138. }
  91139. };
  91140. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  91141. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  91142. if (this.blocks) {
  91143. for (var index = 0; index < this.blocks.length; index++) {
  91144. var block = this.blocks[index];
  91145. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  91146. }
  91147. return;
  91148. }
  91149. if (allowDuplicate) {
  91150. selection.concat(this.entries);
  91151. }
  91152. else {
  91153. selection.concatWithNoDuplicate(this.entries);
  91154. }
  91155. }
  91156. };
  91157. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  91158. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  91159. if (this.blocks) {
  91160. for (var index = 0; index < this.blocks.length; index++) {
  91161. var block = this.blocks[index];
  91162. block.intersectsRay(ray, selection);
  91163. }
  91164. return;
  91165. }
  91166. selection.concatWithNoDuplicate(this.entries);
  91167. }
  91168. };
  91169. OctreeBlock.prototype.createInnerBlocks = function () {
  91170. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  91171. };
  91172. return OctreeBlock;
  91173. }());
  91174. BABYLON.OctreeBlock = OctreeBlock;
  91175. })(BABYLON || (BABYLON = {}));
  91176. //# sourceMappingURL=babylon.octreeBlock.js.map
  91177. var BABYLON;
  91178. (function (BABYLON) {
  91179. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  91180. __extends(VRDistortionCorrectionPostProcess, _super);
  91181. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  91182. var _this = _super.call(this, name, "vrDistortionCorrection", [
  91183. 'LensCenter',
  91184. 'Scale',
  91185. 'ScaleIn',
  91186. 'HmdWarpParam'
  91187. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  91188. _this._isRightEye = isRightEye;
  91189. _this._distortionFactors = vrMetrics.distortionK;
  91190. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  91191. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  91192. _this.adaptScaleToCurrentViewport = true;
  91193. _this.onSizeChangedObservable.add(function () {
  91194. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  91195. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  91196. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  91197. });
  91198. _this.onApplyObservable.add(function (effect) {
  91199. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  91200. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  91201. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  91202. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  91203. });
  91204. return _this;
  91205. }
  91206. return VRDistortionCorrectionPostProcess;
  91207. }(BABYLON.PostProcess));
  91208. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  91209. })(BABYLON || (BABYLON = {}));
  91210. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  91211. var BABYLON;
  91212. (function (BABYLON) {
  91213. /**
  91214. * Postprocess used to generate anaglyphic rendering
  91215. */
  91216. var AnaglyphPostProcess = /** @class */ (function (_super) {
  91217. __extends(AnaglyphPostProcess, _super);
  91218. /**
  91219. * Creates a new AnaglyphPostProcess
  91220. * @param name defines postprocess name
  91221. * @param options defines creation options or target ratio scale
  91222. * @param rigCameras defines cameras using this postprocess
  91223. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  91224. * @param engine defines hosting engine
  91225. * @param reusable defines if the postprocess will be reused multiple times per frame
  91226. */
  91227. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  91228. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  91229. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91230. _this.onApplyObservable.add(function (effect) {
  91231. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  91232. });
  91233. return _this;
  91234. }
  91235. return AnaglyphPostProcess;
  91236. }(BABYLON.PostProcess));
  91237. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  91238. })(BABYLON || (BABYLON = {}));
  91239. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  91240. var BABYLON;
  91241. (function (BABYLON) {
  91242. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  91243. __extends(StereoscopicInterlacePostProcess, _super);
  91244. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  91245. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  91246. _this._passedProcess = rigCameras[0]._rigPostProcess;
  91247. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91248. _this.onSizeChangedObservable.add(function () {
  91249. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  91250. });
  91251. _this.onApplyObservable.add(function (effect) {
  91252. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  91253. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  91254. });
  91255. return _this;
  91256. }
  91257. return StereoscopicInterlacePostProcess;
  91258. }(BABYLON.PostProcess));
  91259. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  91260. })(BABYLON || (BABYLON = {}));
  91261. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  91262. var BABYLON;
  91263. (function (BABYLON) {
  91264. /**
  91265. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  91266. * Screen rotation is taken into account.
  91267. */
  91268. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  91269. function FreeCameraDeviceOrientationInput() {
  91270. var _this = this;
  91271. this._screenOrientationAngle = 0;
  91272. this._screenQuaternion = new BABYLON.Quaternion();
  91273. this._alpha = 0;
  91274. this._beta = 0;
  91275. this._gamma = 0;
  91276. this._orientationChanged = function () {
  91277. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  91278. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  91279. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  91280. };
  91281. this._deviceOrientation = function (evt) {
  91282. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  91283. _this._beta = evt.beta !== null ? evt.beta : 0;
  91284. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  91285. };
  91286. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  91287. this._orientationChanged();
  91288. }
  91289. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  91290. get: function () {
  91291. return this._camera;
  91292. },
  91293. set: function (camera) {
  91294. this._camera = camera;
  91295. if (this._camera != null && !this._camera.rotationQuaternion) {
  91296. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  91297. }
  91298. },
  91299. enumerable: true,
  91300. configurable: true
  91301. });
  91302. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91303. window.addEventListener("orientationchange", this._orientationChanged);
  91304. window.addEventListener("deviceorientation", this._deviceOrientation);
  91305. //In certain cases, the attach control is called AFTER orientation was changed,
  91306. //So this is needed.
  91307. this._orientationChanged();
  91308. };
  91309. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  91310. window.removeEventListener("orientationchange", this._orientationChanged);
  91311. window.removeEventListener("deviceorientation", this._deviceOrientation);
  91312. };
  91313. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  91314. //if no device orientation provided, don't update the rotation.
  91315. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  91316. if (!this._alpha)
  91317. return;
  91318. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  91319. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  91320. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  91321. //Mirror on XY Plane
  91322. this._camera.rotationQuaternion.z *= -1;
  91323. this._camera.rotationQuaternion.w *= -1;
  91324. };
  91325. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  91326. return "FreeCameraDeviceOrientationInput";
  91327. };
  91328. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  91329. return "deviceOrientation";
  91330. };
  91331. return FreeCameraDeviceOrientationInput;
  91332. }());
  91333. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  91334. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  91335. })(BABYLON || (BABYLON = {}));
  91336. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  91337. var BABYLON;
  91338. (function (BABYLON) {
  91339. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  91340. function ArcRotateCameraVRDeviceOrientationInput() {
  91341. this.alphaCorrection = 1;
  91342. this.betaCorrection = 1;
  91343. this.gammaCorrection = 1;
  91344. this._alpha = 0;
  91345. this._gamma = 0;
  91346. this._dirty = false;
  91347. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  91348. }
  91349. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  91350. this.camera.attachControl(element, noPreventDefault);
  91351. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  91352. };
  91353. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  91354. if (evt.alpha !== null) {
  91355. this._alpha = +evt.alpha | 0;
  91356. }
  91357. if (evt.gamma !== null) {
  91358. this._gamma = +evt.gamma | 0;
  91359. }
  91360. this._dirty = true;
  91361. };
  91362. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  91363. if (this._dirty) {
  91364. this._dirty = false;
  91365. if (this._gamma < 0) {
  91366. this._gamma = 180 + this._gamma;
  91367. }
  91368. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  91369. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  91370. }
  91371. };
  91372. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  91373. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  91374. };
  91375. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  91376. return "ArcRotateCameraVRDeviceOrientationInput";
  91377. };
  91378. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  91379. return "VRDeviceOrientation";
  91380. };
  91381. return ArcRotateCameraVRDeviceOrientationInput;
  91382. }());
  91383. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  91384. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  91385. })(BABYLON || (BABYLON = {}));
  91386. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  91387. var BABYLON;
  91388. (function (BABYLON) {
  91389. var VRCameraMetrics = /** @class */ (function () {
  91390. function VRCameraMetrics() {
  91391. this.compensateDistortion = true;
  91392. }
  91393. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  91394. get: function () {
  91395. return this.hResolution / (2 * this.vResolution);
  91396. },
  91397. enumerable: true,
  91398. configurable: true
  91399. });
  91400. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91401. get: function () {
  91402. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91403. },
  91404. enumerable: true,
  91405. configurable: true
  91406. });
  91407. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91408. get: function () {
  91409. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91410. var h = (4 * meters) / this.hScreenSize;
  91411. return BABYLON.Matrix.Translation(h, 0, 0);
  91412. },
  91413. enumerable: true,
  91414. configurable: true
  91415. });
  91416. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91417. get: function () {
  91418. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91419. var h = (4 * meters) / this.hScreenSize;
  91420. return BABYLON.Matrix.Translation(-h, 0, 0);
  91421. },
  91422. enumerable: true,
  91423. configurable: true
  91424. });
  91425. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91426. get: function () {
  91427. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91428. },
  91429. enumerable: true,
  91430. configurable: true
  91431. });
  91432. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91433. get: function () {
  91434. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91435. },
  91436. enumerable: true,
  91437. configurable: true
  91438. });
  91439. VRCameraMetrics.GetDefault = function () {
  91440. var result = new VRCameraMetrics();
  91441. result.hResolution = 1280;
  91442. result.vResolution = 800;
  91443. result.hScreenSize = 0.149759993;
  91444. result.vScreenSize = 0.0935999975;
  91445. result.vScreenCenter = 0.0467999987;
  91446. result.eyeToScreenDistance = 0.0410000011;
  91447. result.lensSeparationDistance = 0.0635000020;
  91448. result.interpupillaryDistance = 0.0640000030;
  91449. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91450. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91451. result.postProcessScaleFactor = 1.714605507808412;
  91452. result.lensCenterOffset = 0.151976421;
  91453. return result;
  91454. };
  91455. return VRCameraMetrics;
  91456. }());
  91457. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91458. })(BABYLON || (BABYLON = {}));
  91459. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91460. var BABYLON;
  91461. (function (BABYLON) {
  91462. /**
  91463. * This represents a WebVR camera.
  91464. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91465. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91466. */
  91467. var WebVRFreeCamera = /** @class */ (function (_super) {
  91468. __extends(WebVRFreeCamera, _super);
  91469. /**
  91470. * Instantiates a WebVRFreeCamera.
  91471. * @param name The name of the WebVRFreeCamera
  91472. * @param position The starting anchor position for the camera
  91473. * @param scene The scene the camera belongs to
  91474. * @param webVROptions a set of customizable options for the webVRCamera
  91475. */
  91476. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91477. if (webVROptions === void 0) { webVROptions = {}; }
  91478. var _this = _super.call(this, name, position, scene) || this;
  91479. _this.webVROptions = webVROptions;
  91480. /**
  91481. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91482. */
  91483. _this._vrDevice = null;
  91484. /**
  91485. * The rawPose of the vrDevice.
  91486. */
  91487. _this.rawPose = null;
  91488. _this._specsVersion = "1.1";
  91489. _this._attached = false;
  91490. _this._descendants = [];
  91491. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91492. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91493. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91494. _this._standingMatrix = null;
  91495. /**
  91496. * Represents device position in babylon space.
  91497. */
  91498. _this.devicePosition = BABYLON.Vector3.Zero();
  91499. /**
  91500. * Represents device rotation in babylon space.
  91501. */
  91502. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91503. /**
  91504. * The scale of the device to be used when translating from device space to babylon space.
  91505. */
  91506. _this.deviceScaleFactor = 1;
  91507. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91508. _this._worldToDevice = BABYLON.Matrix.Identity();
  91509. /**
  91510. * References to the webVR controllers for the vrDevice.
  91511. */
  91512. _this.controllers = [];
  91513. /**
  91514. * Emits an event when a controller is attached.
  91515. */
  91516. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91517. /**
  91518. * Emits an event when a controller's mesh has been loaded;
  91519. */
  91520. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91521. /**
  91522. * If the rig cameras be used as parent instead of this camera.
  91523. */
  91524. _this.rigParenting = true;
  91525. _this._defaultHeight = undefined;
  91526. _this._workingVector = BABYLON.Vector3.Zero();
  91527. _this._oneVector = BABYLON.Vector3.One();
  91528. _this._workingMatrix = BABYLON.Matrix.Identity();
  91529. _this._cache.position = BABYLON.Vector3.Zero();
  91530. if (webVROptions.defaultHeight) {
  91531. _this._defaultHeight = webVROptions.defaultHeight;
  91532. _this.position.y = _this._defaultHeight;
  91533. }
  91534. _this.minZ = 0.1;
  91535. //legacy support - the compensation boolean was removed.
  91536. if (arguments.length === 5) {
  91537. _this.webVROptions = arguments[4];
  91538. }
  91539. // default webVR options
  91540. if (_this.webVROptions.trackPosition == undefined) {
  91541. _this.webVROptions.trackPosition = true;
  91542. }
  91543. if (_this.webVROptions.controllerMeshes == undefined) {
  91544. _this.webVROptions.controllerMeshes = true;
  91545. }
  91546. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91547. _this.webVROptions.defaultLightingOnControllers = true;
  91548. }
  91549. _this.rotationQuaternion = new BABYLON.Quaternion();
  91550. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91551. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91552. }
  91553. //enable VR
  91554. var engine = _this.getEngine();
  91555. _this._onVREnabled = function (success) { if (success) {
  91556. _this.initControllers();
  91557. } };
  91558. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91559. engine.initWebVR().add(function (event) {
  91560. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91561. return;
  91562. }
  91563. _this._vrDevice = event.vrDisplay;
  91564. //reset the rig parameters.
  91565. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91566. if (_this._attached) {
  91567. _this.getEngine().enableVR();
  91568. }
  91569. });
  91570. if (typeof (VRFrameData) !== "undefined")
  91571. _this._frameData = new VRFrameData();
  91572. /**
  91573. * The idea behind the following lines:
  91574. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91575. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91576. * the second will not show it correctly.
  91577. *
  91578. * To solve this - each object that has the camera as parent will be added to a protected array.
  91579. * When the rig camera renders, it will take this array and set all of those to be its children.
  91580. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91581. * Amazing!
  91582. */
  91583. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91584. if (camera.parent === _this && _this.rigParenting) {
  91585. _this._descendants = _this.getDescendants(true, function (n) {
  91586. // don't take the cameras or the controllers!
  91587. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91588. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91589. return !isController && !isRigCamera;
  91590. });
  91591. _this._descendants.forEach(function (node) {
  91592. node.parent = camera;
  91593. });
  91594. }
  91595. });
  91596. scene.onAfterCameraRenderObservable.add(function (camera) {
  91597. if (camera.parent === _this && _this.rigParenting) {
  91598. _this._descendants.forEach(function (node) {
  91599. node.parent = _this;
  91600. });
  91601. }
  91602. });
  91603. return _this;
  91604. }
  91605. /**
  91606. * Gets the device distance from the ground in meters.
  91607. * @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.
  91608. */
  91609. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91610. if (this._standingMatrix) {
  91611. // Add standing matrix offset to get real offset from ground in room
  91612. this._standingMatrix.getTranslationToRef(this._workingVector);
  91613. return this._deviceRoomPosition.y + this._workingVector.y;
  91614. }
  91615. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91616. return this._defaultHeight || 0;
  91617. };
  91618. /**
  91619. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91620. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91621. */
  91622. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91623. var _this = this;
  91624. if (callback === void 0) { callback = function (bool) { }; }
  91625. // Use standing matrix if available
  91626. this.getEngine().initWebVRAsync().then(function (result) {
  91627. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91628. callback(false);
  91629. }
  91630. else {
  91631. _this._standingMatrix = new BABYLON.Matrix();
  91632. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91633. if (!_this.getScene().useRightHandedSystem) {
  91634. [2, 6, 8, 9, 14].forEach(function (num) {
  91635. if (_this._standingMatrix) {
  91636. _this._standingMatrix.m[num] *= -1;
  91637. }
  91638. });
  91639. }
  91640. callback(true);
  91641. }
  91642. });
  91643. };
  91644. /**
  91645. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91646. * @returns A promise with a boolean set to if the standing matrix is supported.
  91647. */
  91648. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91649. var _this = this;
  91650. return new Promise(function (res, rej) {
  91651. _this.useStandingMatrix(function (supported) {
  91652. res(supported);
  91653. });
  91654. });
  91655. };
  91656. /**
  91657. * Disposes the camera
  91658. */
  91659. WebVRFreeCamera.prototype.dispose = function () {
  91660. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91661. _super.prototype.dispose.call(this);
  91662. };
  91663. /**
  91664. * Gets a vrController by name.
  91665. * @param name The name of the controller to retreive
  91666. * @returns the controller matching the name specified or null if not found
  91667. */
  91668. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91669. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91670. var gp = _a[_i];
  91671. if (gp.hand === name) {
  91672. return gp;
  91673. }
  91674. }
  91675. return null;
  91676. };
  91677. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91678. /**
  91679. * The controller corrisponding to the users left hand.
  91680. */
  91681. get: function () {
  91682. if (!this._leftController) {
  91683. this._leftController = this.getControllerByName("left");
  91684. }
  91685. return this._leftController;
  91686. },
  91687. enumerable: true,
  91688. configurable: true
  91689. });
  91690. ;
  91691. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91692. /**
  91693. * The controller corrisponding to the users right hand.
  91694. */
  91695. get: function () {
  91696. if (!this._rightController) {
  91697. this._rightController = this.getControllerByName("right");
  91698. }
  91699. return this._rightController;
  91700. },
  91701. enumerable: true,
  91702. configurable: true
  91703. });
  91704. ;
  91705. /**
  91706. * Casts a ray forward from the vrCamera's gaze.
  91707. * @param length Length of the ray (default: 100)
  91708. * @returns the ray corrisponding to the gaze
  91709. */
  91710. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91711. if (length === void 0) { length = 100; }
  91712. if (this.leftCamera) {
  91713. // Use left eye to avoid computation to compute center on every call
  91714. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91715. }
  91716. else {
  91717. return _super.prototype.getForwardRay.call(this, length);
  91718. }
  91719. };
  91720. /**
  91721. * Updates the camera based on device's frame data
  91722. */
  91723. WebVRFreeCamera.prototype._checkInputs = function () {
  91724. if (this._vrDevice && this._vrDevice.isPresenting) {
  91725. this._vrDevice.getFrameData(this._frameData);
  91726. this.updateFromDevice(this._frameData.pose);
  91727. }
  91728. _super.prototype._checkInputs.call(this);
  91729. };
  91730. /**
  91731. * Updates the poseControlled values based on the input device pose.
  91732. * @param poseData Pose coming from the device
  91733. */
  91734. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91735. if (poseData && poseData.orientation) {
  91736. this.rawPose = poseData;
  91737. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91738. if (this.getScene().useRightHandedSystem) {
  91739. this._deviceRoomRotationQuaternion.z *= -1;
  91740. this._deviceRoomRotationQuaternion.w *= -1;
  91741. }
  91742. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91743. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91744. if (this.getScene().useRightHandedSystem) {
  91745. this._deviceRoomPosition.z *= -1;
  91746. }
  91747. }
  91748. }
  91749. };
  91750. /**
  91751. * WebVR's attach control will start broadcasting frames to the device.
  91752. * Note that in certain browsers (chrome for example) this function must be called
  91753. * within a user-interaction callback. Example:
  91754. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91755. *
  91756. * @param element html element to attach the vrDevice to
  91757. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91758. */
  91759. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91760. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91761. this._attached = true;
  91762. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91763. if (this._vrDevice) {
  91764. this.getEngine().enableVR();
  91765. }
  91766. };
  91767. /**
  91768. * Detaches the camera from the html element and disables VR
  91769. *
  91770. * @param element html element to detach from
  91771. */
  91772. WebVRFreeCamera.prototype.detachControl = function (element) {
  91773. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91774. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91775. _super.prototype.detachControl.call(this, element);
  91776. this._attached = false;
  91777. this.getEngine().disableVR();
  91778. };
  91779. /**
  91780. * @returns the name of this class
  91781. */
  91782. WebVRFreeCamera.prototype.getClassName = function () {
  91783. return "WebVRFreeCamera";
  91784. };
  91785. /**
  91786. * Calls resetPose on the vrDisplay
  91787. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91788. */
  91789. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91790. //uses the vrDisplay's "resetPose()".
  91791. //pitch and roll won't be affected.
  91792. this._vrDevice.resetPose();
  91793. };
  91794. /**
  91795. * Updates the rig cameras (left and right eye)
  91796. */
  91797. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91798. var camLeft = this._rigCameras[0];
  91799. var camRight = this._rigCameras[1];
  91800. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91801. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91802. camLeft.position.copyFrom(this._deviceRoomPosition);
  91803. camRight.position.copyFrom(this._deviceRoomPosition);
  91804. };
  91805. /**
  91806. * Updates the cached values of the camera
  91807. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91808. */
  91809. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91810. var _this = this;
  91811. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91812. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91813. if (!this.updateCacheCalled) {
  91814. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91815. this.updateCacheCalled = true;
  91816. this.update();
  91817. }
  91818. // Set working vector to the device position in room space rotated by the new rotation
  91819. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91820. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91821. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91822. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91823. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91824. // Add translation from anchor position
  91825. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91826. this._workingVector.addInPlace(this.position);
  91827. this._workingVector.subtractInPlace(this._cache.position);
  91828. this._deviceToWorld.setTranslation(this._workingVector);
  91829. // Set an inverted matrix to be used when updating the camera
  91830. this._deviceToWorld.invertToRef(this._worldToDevice);
  91831. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91832. this.controllers.forEach(function (controller) {
  91833. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91834. controller.update();
  91835. });
  91836. }
  91837. if (!ignoreParentClass) {
  91838. _super.prototype._updateCache.call(this);
  91839. }
  91840. this.updateCacheCalled = false;
  91841. };
  91842. /**
  91843. * Updates the current device position and rotation in the babylon world
  91844. */
  91845. WebVRFreeCamera.prototype.update = function () {
  91846. // Get current device position in babylon world
  91847. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91848. // Get current device rotation in babylon world
  91849. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91850. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91851. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91852. _super.prototype.update.call(this);
  91853. };
  91854. /**
  91855. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91856. * @returns an identity matrix
  91857. */
  91858. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91859. return BABYLON.Matrix.Identity();
  91860. };
  91861. /**
  91862. * This function is called by the two RIG cameras.
  91863. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91864. */
  91865. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91866. var _this = this;
  91867. // Update the parent camera prior to using a child camera to avoid desynchronization
  91868. var parentCamera = this._cameraRigParams["parentCamera"];
  91869. parentCamera._updateCache();
  91870. //WebVR 1.1
  91871. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91872. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91873. if (!this.getScene().useRightHandedSystem) {
  91874. [2, 6, 8, 9, 14].forEach(function (num) {
  91875. _this._webvrViewMatrix.m[num] *= -1;
  91876. });
  91877. }
  91878. // update the camera rotation matrix
  91879. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91880. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91881. // Computing target and final matrix
  91882. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91883. // should the view matrix be updated with scale and position offset?
  91884. if (parentCamera.deviceScaleFactor !== 1) {
  91885. this._webvrViewMatrix.invert();
  91886. // scale the position, if set
  91887. if (parentCamera.deviceScaleFactor) {
  91888. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91889. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91890. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91891. }
  91892. this._webvrViewMatrix.invert();
  91893. }
  91894. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91895. // Compute global position
  91896. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91897. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91898. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91899. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91900. this._markSyncedWithParent();
  91901. return this._webvrViewMatrix;
  91902. };
  91903. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91904. var _this = this;
  91905. var parentCamera = this.parent;
  91906. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91907. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91908. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91909. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91910. //babylon compatible matrix
  91911. if (!this.getScene().useRightHandedSystem) {
  91912. [8, 9, 10, 11].forEach(function (num) {
  91913. _this._projectionMatrix.m[num] *= -1;
  91914. });
  91915. }
  91916. return this._projectionMatrix;
  91917. };
  91918. /**
  91919. * Initializes the controllers and their meshes
  91920. */
  91921. WebVRFreeCamera.prototype.initControllers = function () {
  91922. var _this = this;
  91923. this.controllers = [];
  91924. var manager = this.getScene().gamepadManager;
  91925. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91926. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91927. var webVrController = gamepad;
  91928. if (webVrController.defaultModel) {
  91929. webVrController.defaultModel.setEnabled(false);
  91930. }
  91931. if (webVrController.hand === "right") {
  91932. _this._rightController = null;
  91933. }
  91934. if (webVrController.hand === "left") {
  91935. _this._leftController = null;
  91936. }
  91937. var controllerIndex = _this.controllers.indexOf(webVrController);
  91938. if (controllerIndex !== -1) {
  91939. _this.controllers.splice(controllerIndex, 1);
  91940. }
  91941. }
  91942. });
  91943. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91944. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91945. var webVrController_1 = gamepad;
  91946. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91947. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91948. if (_this.webVROptions.controllerMeshes) {
  91949. if (webVrController_1.defaultModel) {
  91950. webVrController_1.defaultModel.setEnabled(true);
  91951. }
  91952. else {
  91953. // Load the meshes
  91954. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91955. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91956. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91957. if (_this.webVROptions.defaultLightingOnControllers) {
  91958. if (!_this._lightOnControllers) {
  91959. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91960. }
  91961. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91962. var children = mesh.getChildren();
  91963. if (children.length !== 0) {
  91964. children.forEach(function (mesh) {
  91965. light.includedOnlyMeshes.push(mesh);
  91966. activateLightOnSubMeshes_1(mesh, light);
  91967. });
  91968. }
  91969. };
  91970. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91971. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91972. }
  91973. });
  91974. }
  91975. }
  91976. webVrController_1.attachToPoseControlledCamera(_this);
  91977. // since this is async - sanity check. Is the controller already stored?
  91978. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91979. //add to the controllers array
  91980. _this.controllers.push(webVrController_1);
  91981. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91982. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91983. // So we're overriding setting left & right manually to be sure
  91984. var firstViveWandDetected = false;
  91985. for (var i = 0; i < _this.controllers.length; i++) {
  91986. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91987. if (!firstViveWandDetected) {
  91988. firstViveWandDetected = true;
  91989. _this.controllers[i].hand = "left";
  91990. }
  91991. else {
  91992. _this.controllers[i].hand = "right";
  91993. }
  91994. }
  91995. }
  91996. //did we find enough controllers? Great! let the developer know.
  91997. if (_this.controllers.length >= 2) {
  91998. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91999. }
  92000. }
  92001. }
  92002. });
  92003. };
  92004. return WebVRFreeCamera;
  92005. }(BABYLON.FreeCamera));
  92006. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  92007. })(BABYLON || (BABYLON = {}));
  92008. //# sourceMappingURL=babylon.webVRCamera.js.map
  92009. var BABYLON;
  92010. (function (BABYLON) {
  92011. // We're mainly based on the logic defined into the FreeCamera code
  92012. /**
  92013. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  92014. * being tilted forward or back and left or right.
  92015. */
  92016. var DeviceOrientationCamera = /** @class */ (function (_super) {
  92017. __extends(DeviceOrientationCamera, _super);
  92018. /**
  92019. * Creates a new device orientation camera
  92020. * @param name The name of the camera
  92021. * @param position The start position camera
  92022. * @param scene The scene the camera belongs to
  92023. */
  92024. function DeviceOrientationCamera(name, position, scene) {
  92025. var _this = _super.call(this, name, position, scene) || this;
  92026. _this._quaternionCache = new BABYLON.Quaternion();
  92027. _this.inputs.addDeviceOrientation();
  92028. return _this;
  92029. }
  92030. /**
  92031. * Gets the current instance class name ("DeviceOrientationCamera").
  92032. * This helps avoiding instanceof at run time.
  92033. * @returns the class name
  92034. */
  92035. DeviceOrientationCamera.prototype.getClassName = function () {
  92036. return "DeviceOrientationCamera";
  92037. };
  92038. /**
  92039. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  92040. */
  92041. DeviceOrientationCamera.prototype._checkInputs = function () {
  92042. _super.prototype._checkInputs.call(this);
  92043. this._quaternionCache.copyFrom(this.rotationQuaternion);
  92044. if (this._initialQuaternion) {
  92045. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92046. }
  92047. };
  92048. /**
  92049. * Reset the camera to its default orientation on the specified axis only.
  92050. * @param axis The axis to reset
  92051. */
  92052. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  92053. var _this = this;
  92054. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  92055. //can only work if this camera has a rotation quaternion already.
  92056. if (!this.rotationQuaternion)
  92057. return;
  92058. if (!this._initialQuaternion) {
  92059. this._initialQuaternion = new BABYLON.Quaternion();
  92060. }
  92061. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  92062. ['x', 'y', 'z'].forEach(function (axisName) {
  92063. if (!axis[axisName]) {
  92064. _this._initialQuaternion[axisName] = 0;
  92065. }
  92066. else {
  92067. _this._initialQuaternion[axisName] *= -1;
  92068. }
  92069. });
  92070. this._initialQuaternion.normalize();
  92071. //force rotation update
  92072. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  92073. };
  92074. return DeviceOrientationCamera;
  92075. }(BABYLON.FreeCamera));
  92076. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  92077. })(BABYLON || (BABYLON = {}));
  92078. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  92079. var BABYLON;
  92080. (function (BABYLON) {
  92081. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  92082. __extends(VRDeviceOrientationFreeCamera, _super);
  92083. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92084. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92085. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92086. var _this = _super.call(this, name, position, scene) || this;
  92087. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92088. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92089. return _this;
  92090. }
  92091. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  92092. return "VRDeviceOrientationFreeCamera";
  92093. };
  92094. return VRDeviceOrientationFreeCamera;
  92095. }(BABYLON.DeviceOrientationCamera));
  92096. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  92097. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  92098. __extends(VRDeviceOrientationGamepadCamera, _super);
  92099. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  92100. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92101. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92102. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  92103. _this.inputs.addGamepad();
  92104. return _this;
  92105. }
  92106. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  92107. return "VRDeviceOrientationGamepadCamera";
  92108. };
  92109. return VRDeviceOrientationGamepadCamera;
  92110. }(VRDeviceOrientationFreeCamera));
  92111. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  92112. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  92113. __extends(VRDeviceOrientationArcRotateCamera, _super);
  92114. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  92115. if (compensateDistortion === void 0) { compensateDistortion = true; }
  92116. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  92117. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92118. vrCameraMetrics.compensateDistortion = compensateDistortion;
  92119. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  92120. _this.inputs.addVRDeviceOrientation();
  92121. return _this;
  92122. }
  92123. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  92124. return "VRDeviceOrientationArcRotateCamera";
  92125. };
  92126. return VRDeviceOrientationArcRotateCamera;
  92127. }(BABYLON.ArcRotateCamera));
  92128. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  92129. })(BABYLON || (BABYLON = {}));
  92130. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  92131. var BABYLON;
  92132. (function (BABYLON) {
  92133. /**
  92134. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  92135. */
  92136. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  92137. __extends(AnaglyphFreeCamera, _super);
  92138. /**
  92139. * Creates a new AnaglyphFreeCamera
  92140. * @param name defines camera name
  92141. * @param position defines initial position
  92142. * @param interaxialDistance defines distance between each color axis
  92143. * @param scene defines the hosting scene
  92144. */
  92145. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  92146. var _this = _super.call(this, name, position, scene) || this;
  92147. _this.interaxialDistance = interaxialDistance;
  92148. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92149. return _this;
  92150. }
  92151. /**
  92152. * Gets camera class name
  92153. * @returns AnaglyphFreeCamera
  92154. */
  92155. AnaglyphFreeCamera.prototype.getClassName = function () {
  92156. return "AnaglyphFreeCamera";
  92157. };
  92158. return AnaglyphFreeCamera;
  92159. }(BABYLON.FreeCamera));
  92160. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  92161. /**
  92162. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  92163. */
  92164. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  92165. __extends(AnaglyphArcRotateCamera, _super);
  92166. /**
  92167. * Creates a new AnaglyphArcRotateCamera
  92168. * @param name defines camera name
  92169. * @param alpha defines alpha angle (in radians)
  92170. * @param beta defines beta angle (in radians)
  92171. * @param radius defines radius
  92172. * @param target defines camera target
  92173. * @param interaxialDistance defines distance between each color axis
  92174. * @param scene defines the hosting scene
  92175. */
  92176. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  92177. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92178. _this.interaxialDistance = interaxialDistance;
  92179. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92180. return _this;
  92181. }
  92182. /**
  92183. * Gets camera class name
  92184. * @returns AnaglyphArcRotateCamera
  92185. */
  92186. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  92187. return "AnaglyphArcRotateCamera";
  92188. };
  92189. return AnaglyphArcRotateCamera;
  92190. }(BABYLON.ArcRotateCamera));
  92191. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  92192. /**
  92193. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  92194. */
  92195. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  92196. __extends(AnaglyphGamepadCamera, _super);
  92197. /**
  92198. * Creates a new AnaglyphGamepadCamera
  92199. * @param name defines camera name
  92200. * @param position defines initial position
  92201. * @param interaxialDistance defines distance between each color axis
  92202. * @param scene defines the hosting scene
  92203. */
  92204. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  92205. var _this = _super.call(this, name, position, scene) || this;
  92206. _this.interaxialDistance = interaxialDistance;
  92207. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92208. return _this;
  92209. }
  92210. /**
  92211. * Gets camera class name
  92212. * @returns AnaglyphGamepadCamera
  92213. */
  92214. AnaglyphGamepadCamera.prototype.getClassName = function () {
  92215. return "AnaglyphGamepadCamera";
  92216. };
  92217. return AnaglyphGamepadCamera;
  92218. }(BABYLON.GamepadCamera));
  92219. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  92220. /**
  92221. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  92222. */
  92223. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  92224. __extends(AnaglyphUniversalCamera, _super);
  92225. /**
  92226. * Creates a new AnaglyphUniversalCamera
  92227. * @param name defines camera name
  92228. * @param position defines initial position
  92229. * @param interaxialDistance defines distance between each color axis
  92230. * @param scene defines the hosting scene
  92231. */
  92232. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  92233. var _this = _super.call(this, name, position, scene) || this;
  92234. _this.interaxialDistance = interaxialDistance;
  92235. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  92236. return _this;
  92237. }
  92238. /**
  92239. * Gets camera class name
  92240. * @returns AnaglyphUniversalCamera
  92241. */
  92242. AnaglyphUniversalCamera.prototype.getClassName = function () {
  92243. return "AnaglyphUniversalCamera";
  92244. };
  92245. return AnaglyphUniversalCamera;
  92246. }(BABYLON.UniversalCamera));
  92247. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  92248. /**
  92249. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  92250. */
  92251. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  92252. __extends(StereoscopicFreeCamera, _super);
  92253. /**
  92254. * Creates a new StereoscopicFreeCamera
  92255. * @param name defines camera name
  92256. * @param position defines initial position
  92257. * @param interaxialDistance defines distance between each color axis
  92258. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92259. * @param scene defines the hosting scene
  92260. */
  92261. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92262. var _this = _super.call(this, name, position, scene) || this;
  92263. _this.interaxialDistance = interaxialDistance;
  92264. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92265. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92266. return _this;
  92267. }
  92268. /**
  92269. * Gets camera class name
  92270. * @returns StereoscopicFreeCamera
  92271. */
  92272. StereoscopicFreeCamera.prototype.getClassName = function () {
  92273. return "StereoscopicFreeCamera";
  92274. };
  92275. return StereoscopicFreeCamera;
  92276. }(BABYLON.FreeCamera));
  92277. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  92278. /**
  92279. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  92280. */
  92281. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  92282. __extends(StereoscopicArcRotateCamera, _super);
  92283. /**
  92284. * Creates a new StereoscopicArcRotateCamera
  92285. * @param name defines camera name
  92286. * @param alpha defines alpha angle (in radians)
  92287. * @param beta defines beta angle (in radians)
  92288. * @param radius defines radius
  92289. * @param target defines camera target
  92290. * @param interaxialDistance defines distance between each color axis
  92291. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92292. * @param scene defines the hosting scene
  92293. */
  92294. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  92295. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  92296. _this.interaxialDistance = interaxialDistance;
  92297. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92298. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92299. return _this;
  92300. }
  92301. /**
  92302. * Gets camera class name
  92303. * @returns StereoscopicArcRotateCamera
  92304. */
  92305. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  92306. return "StereoscopicArcRotateCamera";
  92307. };
  92308. return StereoscopicArcRotateCamera;
  92309. }(BABYLON.ArcRotateCamera));
  92310. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  92311. /**
  92312. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  92313. */
  92314. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  92315. __extends(StereoscopicGamepadCamera, _super);
  92316. /**
  92317. * Creates a new StereoscopicGamepadCamera
  92318. * @param name defines camera name
  92319. * @param position defines initial position
  92320. * @param interaxialDistance defines distance between each color axis
  92321. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92322. * @param scene defines the hosting scene
  92323. */
  92324. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92325. var _this = _super.call(this, name, position, scene) || this;
  92326. _this.interaxialDistance = interaxialDistance;
  92327. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92328. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92329. return _this;
  92330. }
  92331. /**
  92332. * Gets camera class name
  92333. * @returns StereoscopicGamepadCamera
  92334. */
  92335. StereoscopicGamepadCamera.prototype.getClassName = function () {
  92336. return "StereoscopicGamepadCamera";
  92337. };
  92338. return StereoscopicGamepadCamera;
  92339. }(BABYLON.GamepadCamera));
  92340. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  92341. /**
  92342. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  92343. */
  92344. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  92345. __extends(StereoscopicUniversalCamera, _super);
  92346. /**
  92347. * Creates a new StereoscopicUniversalCamera
  92348. * @param name defines camera name
  92349. * @param position defines initial position
  92350. * @param interaxialDistance defines distance between each color axis
  92351. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  92352. * @param scene defines the hosting scene
  92353. */
  92354. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  92355. var _this = _super.call(this, name, position, scene) || this;
  92356. _this.interaxialDistance = interaxialDistance;
  92357. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  92358. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  92359. return _this;
  92360. }
  92361. /**
  92362. * Gets camera class name
  92363. * @returns StereoscopicUniversalCamera
  92364. */
  92365. StereoscopicUniversalCamera.prototype.getClassName = function () {
  92366. return "StereoscopicUniversalCamera";
  92367. };
  92368. return StereoscopicUniversalCamera;
  92369. }(BABYLON.UniversalCamera));
  92370. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  92371. })(BABYLON || (BABYLON = {}));
  92372. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  92373. var BABYLON;
  92374. (function (BABYLON) {
  92375. var VRExperienceHelperGazer = /** @class */ (function () {
  92376. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  92377. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  92378. this.scene = scene;
  92379. this._pointerDownOnMeshAsked = false;
  92380. this._isActionableMesh = false;
  92381. this._teleportationRequestInitiated = false;
  92382. this._teleportationBackRequestInitiated = false;
  92383. this._rotationRightAsked = false;
  92384. this._rotationLeftAsked = false;
  92385. this._dpadPressed = true;
  92386. this._activePointer = false;
  92387. this._id = VRExperienceHelperGazer._idCounter++;
  92388. // Gaze tracker
  92389. if (!gazeTrackerToClone) {
  92390. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  92391. this._gazeTracker.bakeCurrentTransformIntoVertices();
  92392. this._gazeTracker.isPickable = false;
  92393. this._gazeTracker.isVisible = false;
  92394. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92395. targetMat.specularColor = BABYLON.Color3.Black();
  92396. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92397. targetMat.backFaceCulling = false;
  92398. this._gazeTracker.material = targetMat;
  92399. }
  92400. else {
  92401. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92402. }
  92403. }
  92404. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92405. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92406. };
  92407. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92408. this._pointerDownOnMeshAsked = true;
  92409. if (this._currentHit) {
  92410. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92411. }
  92412. };
  92413. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92414. if (this._currentHit) {
  92415. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92416. }
  92417. this._pointerDownOnMeshAsked = false;
  92418. };
  92419. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92420. this._activePointer = true;
  92421. };
  92422. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92423. this._activePointer = false;
  92424. };
  92425. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92426. if (distance === void 0) { distance = 100; }
  92427. };
  92428. VRExperienceHelperGazer.prototype.dispose = function () {
  92429. this._interactionsEnabled = false;
  92430. this._teleportationEnabled = false;
  92431. if (this._gazeTracker) {
  92432. this._gazeTracker.dispose();
  92433. }
  92434. };
  92435. VRExperienceHelperGazer._idCounter = 0;
  92436. return VRExperienceHelperGazer;
  92437. }());
  92438. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92439. __extends(VRExperienceHelperControllerGazer, _super);
  92440. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92441. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92442. _this.webVRController = webVRController;
  92443. // Laser pointer
  92444. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92445. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92446. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92447. laserPointerMaterial.alpha = 0.6;
  92448. _this._laserPointer.material = laserPointerMaterial;
  92449. _this._laserPointer.rotation.x = Math.PI / 2;
  92450. _this._laserPointer.position.z = -0.5;
  92451. _this._laserPointer.isVisible = false;
  92452. _this._laserPointer.isPickable = false;
  92453. if (!webVRController.mesh) {
  92454. // Create an empty mesh that is used prior to loading the high quality model
  92455. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92456. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92457. preloadPointerPose.rotation.x = -0.7;
  92458. preloadMesh.addChild(preloadPointerPose);
  92459. webVRController.attachToMesh(preloadMesh);
  92460. }
  92461. _this._setLaserPointerParent(webVRController.mesh);
  92462. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92463. _this._setLaserPointerParent(mesh);
  92464. });
  92465. return _this;
  92466. }
  92467. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92468. return this.webVRController.getForwardRay(length);
  92469. };
  92470. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92471. _super.prototype._activatePointer.call(this);
  92472. this._laserPointer.isVisible = true;
  92473. };
  92474. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92475. _super.prototype._deactivatePointer.call(this);
  92476. this._laserPointer.isVisible = false;
  92477. };
  92478. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92479. this._laserPointer.material.emissiveColor = color;
  92480. };
  92481. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92482. var makeNotPick = function (root) {
  92483. root.name += " laserPointer";
  92484. root.isPickable = false;
  92485. root.getChildMeshes().forEach(function (c) {
  92486. makeNotPick(c);
  92487. });
  92488. };
  92489. makeNotPick(mesh);
  92490. var childMeshes = mesh.getChildMeshes();
  92491. this.webVRController._pointingPoseNode = null;
  92492. for (var i = 0; i < childMeshes.length; i++) {
  92493. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92494. mesh = childMeshes[i];
  92495. this.webVRController._pointingPoseNode = mesh;
  92496. break;
  92497. }
  92498. }
  92499. this._laserPointer.parent = mesh;
  92500. };
  92501. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92502. if (distance === void 0) { distance = 100; }
  92503. this._laserPointer.scaling.y = distance;
  92504. this._laserPointer.position.z = -distance / 2;
  92505. };
  92506. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92507. _super.prototype.dispose.call(this);
  92508. this._laserPointer.dispose();
  92509. if (this._meshAttachedObserver) {
  92510. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92511. }
  92512. };
  92513. return VRExperienceHelperControllerGazer;
  92514. }(VRExperienceHelperGazer));
  92515. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92516. __extends(VRExperienceHelperCameraGazer, _super);
  92517. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92518. var _this = _super.call(this, scene) || this;
  92519. _this.getCamera = getCamera;
  92520. return _this;
  92521. }
  92522. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92523. var camera = this.getCamera();
  92524. if (camera) {
  92525. return camera.getForwardRay(length);
  92526. }
  92527. else {
  92528. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92529. }
  92530. };
  92531. return VRExperienceHelperCameraGazer;
  92532. }(VRExperienceHelperGazer));
  92533. /**
  92534. * Helps to quickly add VR support to an existing scene.
  92535. * See http://doc.babylonjs.com/how_to/webvr_helper
  92536. */
  92537. var VRExperienceHelper = /** @class */ (function () {
  92538. /**
  92539. * Instantiates a VRExperienceHelper.
  92540. * Helps to quickly add VR support to an existing scene.
  92541. * @param scene The scene the VRExperienceHelper belongs to.
  92542. * @param webVROptions Options to modify the vr experience helper's behavior.
  92543. */
  92544. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92545. if (webVROptions === void 0) { webVROptions = {}; }
  92546. var _this = this;
  92547. this.webVROptions = webVROptions;
  92548. // Can the system support WebVR, even if a headset isn't plugged in?
  92549. this._webVRsupported = false;
  92550. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92551. this._webVRready = false;
  92552. // Are we waiting for the requestPresent callback to complete?
  92553. this._webVRrequesting = false;
  92554. // Are we presenting to the headset right now?
  92555. this._webVRpresenting = false;
  92556. // Are we presenting in the fullscreen fallback?
  92557. this._fullscreenVRpresenting = false;
  92558. /**
  92559. * Observable raised when entering VR.
  92560. */
  92561. this.onEnteringVRObservable = new BABYLON.Observable();
  92562. /**
  92563. * Observable raised when exiting VR.
  92564. */
  92565. this.onExitingVRObservable = new BABYLON.Observable();
  92566. /**
  92567. * Observable raised when controller mesh is loaded.
  92568. */
  92569. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92570. this._useCustomVRButton = false;
  92571. this._teleportationRequested = false;
  92572. this._teleportActive = false;
  92573. this._floorMeshesCollection = [];
  92574. this._rotationAllowed = true;
  92575. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92576. this._isDefaultTeleportationTarget = true;
  92577. this._teleportationFillColor = "#444444";
  92578. this._teleportationBorderColor = "#FFFFFF";
  92579. this._rotationAngle = 0;
  92580. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92581. this._padSensibilityUp = 0.65;
  92582. this._padSensibilityDown = 0.35;
  92583. this.leftController = null;
  92584. this.rightController = null;
  92585. /**
  92586. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92587. */
  92588. this.onNewMeshSelected = new BABYLON.Observable();
  92589. /**
  92590. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92591. */
  92592. this.onNewMeshPicked = new BABYLON.Observable();
  92593. /**
  92594. * Observable raised before camera teleportation
  92595. */
  92596. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92597. /**
  92598. * Observable raised after camera teleportation
  92599. */
  92600. this.onAfterCameraTeleport = new BABYLON.Observable();
  92601. /**
  92602. * Observable raised when current selected mesh gets unselected
  92603. */
  92604. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92605. /**
  92606. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92607. */
  92608. this.teleportationEnabled = true;
  92609. this._teleportationInitialized = false;
  92610. this._interactionsEnabled = false;
  92611. this._interactionsRequested = false;
  92612. this._displayGaze = true;
  92613. this._displayLaserPointer = true;
  92614. this._onResize = function () {
  92615. _this.moveButtonToBottomRight();
  92616. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92617. _this.exitVR();
  92618. }
  92619. };
  92620. this._onFullscreenChange = function () {
  92621. if (document.fullscreen !== undefined) {
  92622. _this._fullscreenVRpresenting = document.fullscreen;
  92623. }
  92624. else if (document.mozFullScreen !== undefined) {
  92625. _this._fullscreenVRpresenting = document.mozFullScreen;
  92626. }
  92627. else if (document.webkitIsFullScreen !== undefined) {
  92628. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92629. }
  92630. else if (document.msIsFullScreen !== undefined) {
  92631. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92632. }
  92633. else if (document.msFullscreenElement !== undefined) {
  92634. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92635. }
  92636. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92637. _this.exitVR();
  92638. if (!_this._useCustomVRButton) {
  92639. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92640. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92641. }
  92642. }
  92643. };
  92644. this.beforeRender = function () {
  92645. if (_this.leftController && _this.leftController._activePointer) {
  92646. _this._castRayAndSelectObject(_this.leftController);
  92647. }
  92648. if (_this.rightController && _this.rightController._activePointer) {
  92649. _this._castRayAndSelectObject(_this.rightController);
  92650. }
  92651. if (_this._noControllerIsActive) {
  92652. _this._castRayAndSelectObject(_this._cameraGazer);
  92653. }
  92654. else {
  92655. _this._cameraGazer._gazeTracker.isVisible = false;
  92656. }
  92657. };
  92658. this._onNewGamepadConnected = function (gamepad) {
  92659. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92660. if (gamepad.leftStick) {
  92661. gamepad.onleftstickchanged(function (stickValues) {
  92662. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92663. // Listening to classic/xbox gamepad only if no VR controller is active
  92664. if ((!_this.leftController && !_this.rightController) ||
  92665. ((_this.leftController && !_this.leftController._activePointer) &&
  92666. (_this.rightController && !_this.rightController._activePointer))) {
  92667. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92668. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92669. }
  92670. }
  92671. });
  92672. }
  92673. if (gamepad.rightStick) {
  92674. gamepad.onrightstickchanged(function (stickValues) {
  92675. if (_this._teleportationInitialized) {
  92676. _this._checkRotate(stickValues, _this._cameraGazer);
  92677. }
  92678. });
  92679. }
  92680. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92681. gamepad.onbuttondown(function (buttonPressed) {
  92682. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92683. _this._cameraGazer._selectionPointerDown();
  92684. }
  92685. });
  92686. gamepad.onbuttonup(function (buttonPressed) {
  92687. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92688. _this._cameraGazer._selectionPointerUp();
  92689. }
  92690. });
  92691. }
  92692. }
  92693. else {
  92694. var webVRController = gamepad;
  92695. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92696. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92697. _this.rightController = controller;
  92698. }
  92699. else {
  92700. _this.leftController = controller;
  92701. }
  92702. _this._tryEnableInteractionOnController(controller);
  92703. }
  92704. };
  92705. // 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
  92706. this._tryEnableInteractionOnController = function (controller) {
  92707. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92708. _this._enableInteractionOnController(controller);
  92709. }
  92710. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92711. _this._enableTeleportationOnController(controller);
  92712. }
  92713. };
  92714. this._onNewGamepadDisconnected = function (gamepad) {
  92715. if (gamepad instanceof BABYLON.WebVRController) {
  92716. if (gamepad.hand === "left" && _this.leftController != null) {
  92717. _this.leftController.dispose();
  92718. _this.leftController = null;
  92719. }
  92720. if (gamepad.hand === "right" && _this.rightController != null) {
  92721. _this.rightController.dispose();
  92722. _this.rightController = null;
  92723. }
  92724. }
  92725. };
  92726. this._workingVector = BABYLON.Vector3.Zero();
  92727. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92728. this._workingMatrix = BABYLON.Matrix.Identity();
  92729. this._scene = scene;
  92730. this._canvas = scene.getEngine().getRenderingCanvas();
  92731. // Parse options
  92732. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92733. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92734. }
  92735. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92736. webVROptions.createDeviceOrientationCamera = true;
  92737. }
  92738. if (webVROptions.laserToggle === undefined) {
  92739. webVROptions.laserToggle = true;
  92740. }
  92741. if (webVROptions.defaultHeight === undefined) {
  92742. webVROptions.defaultHeight = 1.7;
  92743. }
  92744. if (webVROptions.useCustomVRButton) {
  92745. this._useCustomVRButton = true;
  92746. if (webVROptions.customVRButton) {
  92747. this._btnVR = webVROptions.customVRButton;
  92748. }
  92749. }
  92750. if (webVROptions.rayLength) {
  92751. this._rayLength = webVROptions.rayLength;
  92752. }
  92753. this._defaultHeight = webVROptions.defaultHeight;
  92754. if (webVROptions.positionScale) {
  92755. this._rayLength *= webVROptions.positionScale;
  92756. this._defaultHeight *= webVROptions.positionScale;
  92757. }
  92758. // Set position
  92759. if (this._scene.activeCamera) {
  92760. this._position = this._scene.activeCamera.position.clone();
  92761. }
  92762. else {
  92763. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92764. }
  92765. // Set non-vr camera
  92766. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92767. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92768. // Copy data from existing camera
  92769. if (this._scene.activeCamera) {
  92770. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92771. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92772. // Set rotation from previous camera
  92773. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92774. var targetCamera = this._scene.activeCamera;
  92775. if (targetCamera.rotationQuaternion) {
  92776. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92777. }
  92778. else {
  92779. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92780. }
  92781. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92782. }
  92783. }
  92784. this._scene.activeCamera = this._deviceOrientationCamera;
  92785. if (this._canvas) {
  92786. this._scene.activeCamera.attachControl(this._canvas);
  92787. }
  92788. }
  92789. else {
  92790. this._existingCamera = this._scene.activeCamera;
  92791. }
  92792. // Create VR cameras
  92793. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92794. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92795. }
  92796. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92797. this._webVRCamera.useStandingMatrix();
  92798. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92799. // Create default button
  92800. if (!this._useCustomVRButton) {
  92801. this._btnVR = document.createElement("BUTTON");
  92802. this._btnVR.className = "babylonVRicon";
  92803. this._btnVR.id = "babylonVRiconbtn";
  92804. this._btnVR.title = "Click to switch to VR";
  92805. 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) }";
  92806. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92807. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92808. // css += ".babylonVRicon.vrdisplaysupported { }";
  92809. // css += ".babylonVRicon.vrdisplayready { }";
  92810. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92811. var style = document.createElement('style');
  92812. style.appendChild(document.createTextNode(css));
  92813. document.getElementsByTagName('head')[0].appendChild(style);
  92814. this.moveButtonToBottomRight();
  92815. }
  92816. // VR button click event
  92817. if (this._btnVR) {
  92818. this._btnVR.addEventListener("click", function () {
  92819. if (!_this.isInVRMode) {
  92820. _this.enterVR();
  92821. }
  92822. else {
  92823. _this.exitVR();
  92824. }
  92825. });
  92826. }
  92827. // Window events
  92828. window.addEventListener("resize", this._onResize);
  92829. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92830. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92831. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92832. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92833. document.onmsfullscreenchange = this._onFullscreenChange;
  92834. // Display vr button when headset is connected
  92835. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92836. this.displayVRButton();
  92837. }
  92838. else {
  92839. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92840. if (e.vrDisplay) {
  92841. _this.displayVRButton();
  92842. }
  92843. });
  92844. }
  92845. // Exiting VR mode using 'ESC' key on desktop
  92846. this._onKeyDown = function (event) {
  92847. if (event.keyCode === 27 && _this.isInVRMode) {
  92848. _this.exitVR();
  92849. }
  92850. };
  92851. document.addEventListener("keydown", this._onKeyDown);
  92852. // Exiting VR mode double tapping the touch screen
  92853. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92854. if (_this.isInVRMode) {
  92855. _this.exitVR();
  92856. if (_this._fullscreenVRpresenting) {
  92857. _this._scene.getEngine().switchFullscreen(true);
  92858. }
  92859. }
  92860. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92861. // Listen for WebVR display changes
  92862. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92863. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92864. this._onVRRequestPresentStart = function () {
  92865. _this._webVRrequesting = true;
  92866. _this.updateButtonVisibility();
  92867. };
  92868. this._onVRRequestPresentComplete = function (success) {
  92869. _this._webVRrequesting = false;
  92870. _this.updateButtonVisibility();
  92871. };
  92872. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92873. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92874. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92875. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92876. scene.onDisposeObservable.add(function () {
  92877. _this.dispose();
  92878. });
  92879. // Gamepad connection events
  92880. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92881. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92882. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92883. this.updateButtonVisibility();
  92884. //create easing functions
  92885. this._circleEase = new BABYLON.CircleEase();
  92886. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92887. if (this.webVROptions.floorMeshes) {
  92888. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92889. }
  92890. }
  92891. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92892. /** Return this.onEnteringVRObservable
  92893. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92894. */
  92895. get: function () {
  92896. return this.onEnteringVRObservable;
  92897. },
  92898. enumerable: true,
  92899. configurable: true
  92900. });
  92901. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92902. /** Return this.onExitingVRObservable
  92903. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92904. */
  92905. get: function () {
  92906. return this.onExitingVRObservable;
  92907. },
  92908. enumerable: true,
  92909. configurable: true
  92910. });
  92911. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92912. /** Return this.onControllerMeshLoadedObservable
  92913. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92914. */
  92915. get: function () {
  92916. return this.onControllerMeshLoadedObservable;
  92917. },
  92918. enumerable: true,
  92919. configurable: true
  92920. });
  92921. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92922. /**
  92923. * The mesh used to display where the user is going to teleport.
  92924. */
  92925. get: function () {
  92926. return this._teleportationTarget;
  92927. },
  92928. /**
  92929. * Sets the mesh to be used to display where the user is going to teleport.
  92930. */
  92931. set: function (value) {
  92932. if (value) {
  92933. value.name = "teleportationTarget";
  92934. this._isDefaultTeleportationTarget = false;
  92935. this._teleportationTarget = value;
  92936. }
  92937. },
  92938. enumerable: true,
  92939. configurable: true
  92940. });
  92941. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92942. /**
  92943. * The mesh used to display where the user is selecting,
  92944. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92945. * See http://doc.babylonjs.com/resources/baking_transformations
  92946. */
  92947. get: function () {
  92948. return this._cameraGazer._gazeTracker;
  92949. },
  92950. set: function (value) {
  92951. if (value) {
  92952. this._cameraGazer._gazeTracker = value;
  92953. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92954. this._cameraGazer._gazeTracker.isPickable = false;
  92955. this._cameraGazer._gazeTracker.isVisible = false;
  92956. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92957. if (this.leftController) {
  92958. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92959. }
  92960. if (this.rightController) {
  92961. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92962. }
  92963. }
  92964. },
  92965. enumerable: true,
  92966. configurable: true
  92967. });
  92968. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92969. /**
  92970. * If the ray of the gaze should be displayed.
  92971. */
  92972. get: function () {
  92973. return this._displayGaze;
  92974. },
  92975. /**
  92976. * Sets if the ray of the gaze should be displayed.
  92977. */
  92978. set: function (value) {
  92979. this._displayGaze = value;
  92980. if (!value) {
  92981. this._cameraGazer._gazeTracker.isVisible = false;
  92982. if (this.leftController) {
  92983. this.leftController._gazeTracker.isVisible = false;
  92984. }
  92985. if (this.rightController) {
  92986. this.rightController._gazeTracker.isVisible = false;
  92987. }
  92988. }
  92989. },
  92990. enumerable: true,
  92991. configurable: true
  92992. });
  92993. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92994. /**
  92995. * If the ray of the LaserPointer should be displayed.
  92996. */
  92997. get: function () {
  92998. return this._displayLaserPointer;
  92999. },
  93000. /**
  93001. * Sets if the ray of the LaserPointer should be displayed.
  93002. */
  93003. set: function (value) {
  93004. this._displayLaserPointer = value;
  93005. if (!value) {
  93006. if (this.rightController) {
  93007. this.rightController._deactivatePointer();
  93008. this.rightController._gazeTracker.isVisible = false;
  93009. }
  93010. if (this.leftController) {
  93011. this.leftController._deactivatePointer();
  93012. this.leftController._gazeTracker.isVisible = false;
  93013. }
  93014. }
  93015. else {
  93016. if (this.rightController) {
  93017. this.rightController._activatePointer();
  93018. }
  93019. if (this.leftController) {
  93020. this.leftController._activatePointer();
  93021. }
  93022. }
  93023. },
  93024. enumerable: true,
  93025. configurable: true
  93026. });
  93027. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  93028. /**
  93029. * The deviceOrientationCamera used as the camera when not in VR.
  93030. */
  93031. get: function () {
  93032. return this._deviceOrientationCamera;
  93033. },
  93034. enumerable: true,
  93035. configurable: true
  93036. });
  93037. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  93038. /**
  93039. * Based on the current WebVR support, returns the current VR camera used.
  93040. */
  93041. get: function () {
  93042. if (this._webVRready) {
  93043. return this._webVRCamera;
  93044. }
  93045. else {
  93046. return this._scene.activeCamera;
  93047. }
  93048. },
  93049. enumerable: true,
  93050. configurable: true
  93051. });
  93052. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  93053. /**
  93054. * The webVRCamera which is used when in VR.
  93055. */
  93056. get: function () {
  93057. return this._webVRCamera;
  93058. },
  93059. enumerable: true,
  93060. configurable: true
  93061. });
  93062. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  93063. /**
  93064. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  93065. */
  93066. get: function () {
  93067. return this._vrDeviceOrientationCamera;
  93068. },
  93069. enumerable: true,
  93070. configurable: true
  93071. });
  93072. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  93073. get: function () {
  93074. var result = this._cameraGazer._teleportationRequestInitiated
  93075. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  93076. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  93077. return result;
  93078. },
  93079. enumerable: true,
  93080. configurable: true
  93081. });
  93082. // Raised when one of the controller has loaded successfully its associated default mesh
  93083. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  93084. if (this.leftController && this.leftController.webVRController == webVRController) {
  93085. if (webVRController.mesh) {
  93086. this.leftController._setLaserPointerParent(webVRController.mesh);
  93087. }
  93088. }
  93089. if (this.rightController && this.rightController.webVRController == webVRController) {
  93090. if (webVRController.mesh) {
  93091. this.rightController._setLaserPointerParent(webVRController.mesh);
  93092. }
  93093. }
  93094. try {
  93095. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  93096. }
  93097. catch (err) {
  93098. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  93099. }
  93100. };
  93101. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  93102. /**
  93103. * Gets a value indicating if we are currently in VR mode.
  93104. */
  93105. get: function () {
  93106. return this._webVRpresenting || this._fullscreenVRpresenting;
  93107. },
  93108. enumerable: true,
  93109. configurable: true
  93110. });
  93111. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  93112. var vrDisplay = this._scene.getEngine().getVRDevice();
  93113. if (vrDisplay) {
  93114. var wasPresenting = this._webVRpresenting;
  93115. // A VR display is connected
  93116. this._webVRpresenting = vrDisplay.isPresenting;
  93117. if (wasPresenting && !this._webVRpresenting)
  93118. this.exitVR();
  93119. }
  93120. else {
  93121. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  93122. }
  93123. this.updateButtonVisibility();
  93124. };
  93125. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  93126. this._webVRsupported = eventArgs.vrSupported;
  93127. this._webVRready = !!eventArgs.vrDisplay;
  93128. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  93129. this.updateButtonVisibility();
  93130. };
  93131. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  93132. if (this._canvas && !this._useCustomVRButton) {
  93133. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  93134. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  93135. }
  93136. };
  93137. VRExperienceHelper.prototype.displayVRButton = function () {
  93138. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  93139. document.body.appendChild(this._btnVR);
  93140. this._btnVRDisplayed = true;
  93141. }
  93142. };
  93143. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  93144. if (!this._btnVR || this._useCustomVRButton) {
  93145. return;
  93146. }
  93147. this._btnVR.className = "babylonVRicon";
  93148. if (this.isInVRMode) {
  93149. this._btnVR.className += " vrdisplaypresenting";
  93150. }
  93151. else {
  93152. if (this._webVRready)
  93153. this._btnVR.className += " vrdisplayready";
  93154. if (this._webVRsupported)
  93155. this._btnVR.className += " vrdisplaysupported";
  93156. if (this._webVRrequesting)
  93157. this._btnVR.className += " vrdisplayrequesting";
  93158. }
  93159. };
  93160. /**
  93161. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  93162. * Otherwise, will use the fullscreen API.
  93163. */
  93164. VRExperienceHelper.prototype.enterVR = function () {
  93165. if (this.onEnteringVRObservable) {
  93166. try {
  93167. this.onEnteringVRObservable.notifyObservers(this);
  93168. }
  93169. catch (err) {
  93170. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  93171. }
  93172. }
  93173. if (this._scene.activeCamera) {
  93174. this._position = this._scene.activeCamera.position.clone();
  93175. // make sure that we return to the last active camera
  93176. this._existingCamera = this._scene.activeCamera;
  93177. }
  93178. if (this._webVRrequesting)
  93179. return;
  93180. // If WebVR is supported and a headset is connected
  93181. if (this._webVRready) {
  93182. if (!this._webVRpresenting) {
  93183. this._webVRCamera.position = this._position;
  93184. this._scene.activeCamera = this._webVRCamera;
  93185. }
  93186. }
  93187. else if (this._vrDeviceOrientationCamera) {
  93188. this._vrDeviceOrientationCamera.position = this._position;
  93189. if (this._scene.activeCamera) {
  93190. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  93191. }
  93192. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  93193. this._scene.getEngine().switchFullscreen(true);
  93194. this.updateButtonVisibility();
  93195. }
  93196. if (this._scene.activeCamera && this._canvas) {
  93197. this._scene.activeCamera.attachControl(this._canvas);
  93198. }
  93199. if (this._interactionsEnabled) {
  93200. this._scene.registerBeforeRender(this.beforeRender);
  93201. }
  93202. };
  93203. /**
  93204. * Attempt to exit VR, or fullscreen.
  93205. */
  93206. VRExperienceHelper.prototype.exitVR = function () {
  93207. if (this.onExitingVRObservable) {
  93208. try {
  93209. this.onExitingVRObservable.notifyObservers(this);
  93210. }
  93211. catch (err) {
  93212. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  93213. }
  93214. }
  93215. if (this._webVRpresenting) {
  93216. this._scene.getEngine().disableVR();
  93217. }
  93218. if (this._scene.activeCamera) {
  93219. this._position = this._scene.activeCamera.position.clone();
  93220. }
  93221. if (this._deviceOrientationCamera) {
  93222. this._deviceOrientationCamera.position = this._position;
  93223. this._scene.activeCamera = this._deviceOrientationCamera;
  93224. if (this._canvas) {
  93225. this._scene.activeCamera.attachControl(this._canvas);
  93226. }
  93227. }
  93228. else if (this._existingCamera) {
  93229. this._existingCamera.position = this._position;
  93230. this._scene.activeCamera = this._existingCamera;
  93231. }
  93232. this.updateButtonVisibility();
  93233. if (this._interactionsEnabled) {
  93234. this._scene.unregisterBeforeRender(this.beforeRender);
  93235. }
  93236. // resize to update width and height when exiting vr exits fullscreen
  93237. this._scene.getEngine().resize();
  93238. };
  93239. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  93240. /**
  93241. * The position of the vr experience helper.
  93242. */
  93243. get: function () {
  93244. return this._position;
  93245. },
  93246. /**
  93247. * Sets the position of the vr experience helper.
  93248. */
  93249. set: function (value) {
  93250. this._position = value;
  93251. if (this._scene.activeCamera) {
  93252. this._scene.activeCamera.position = value;
  93253. }
  93254. },
  93255. enumerable: true,
  93256. configurable: true
  93257. });
  93258. /**
  93259. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  93260. */
  93261. VRExperienceHelper.prototype.enableInteractions = function () {
  93262. var _this = this;
  93263. if (!this._interactionsEnabled) {
  93264. this._interactionsRequested = true;
  93265. if (this.leftController) {
  93266. this._enableInteractionOnController(this.leftController);
  93267. }
  93268. if (this.rightController) {
  93269. this._enableInteractionOnController(this.rightController);
  93270. }
  93271. this.raySelectionPredicate = function (mesh) {
  93272. return mesh.isVisible;
  93273. };
  93274. this.meshSelectionPredicate = function (mesh) {
  93275. return true;
  93276. };
  93277. this._raySelectionPredicate = function (mesh) {
  93278. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  93279. && mesh.name.indexOf("teleportationTarget") === -1
  93280. && mesh.name.indexOf("torusTeleportation") === -1
  93281. && mesh.name.indexOf("laserPointer") === -1)) {
  93282. return _this.raySelectionPredicate(mesh);
  93283. }
  93284. return false;
  93285. };
  93286. this._interactionsEnabled = true;
  93287. }
  93288. };
  93289. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  93290. get: function () {
  93291. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  93292. },
  93293. enumerable: true,
  93294. configurable: true
  93295. });
  93296. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  93297. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  93298. if (this._floorMeshesCollection[i].id === mesh.id) {
  93299. return true;
  93300. }
  93301. }
  93302. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  93303. return true;
  93304. }
  93305. return false;
  93306. };
  93307. /**
  93308. * Adds a floor mesh to be used for teleportation.
  93309. * @param floorMesh the mesh to be used for teleportation.
  93310. */
  93311. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  93312. if (!this._floorMeshesCollection) {
  93313. return;
  93314. }
  93315. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  93316. return;
  93317. }
  93318. this._floorMeshesCollection.push(floorMesh);
  93319. };
  93320. /**
  93321. * Removes a floor mesh from being used for teleportation.
  93322. * @param floorMesh the mesh to be removed.
  93323. */
  93324. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  93325. if (!this._floorMeshesCollection) {
  93326. return;
  93327. }
  93328. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  93329. if (meshIndex !== -1) {
  93330. this._floorMeshesCollection.splice(meshIndex, 1);
  93331. }
  93332. };
  93333. /**
  93334. * Enables interactions and teleportation using the VR controllers and gaze.
  93335. * @param vrTeleportationOptions options to modify teleportation behavior.
  93336. */
  93337. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  93338. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  93339. if (!this._teleportationInitialized) {
  93340. this._teleportationRequested = true;
  93341. this.enableInteractions();
  93342. if (vrTeleportationOptions.floorMeshName) {
  93343. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  93344. }
  93345. if (vrTeleportationOptions.floorMeshes) {
  93346. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  93347. }
  93348. if (this.leftController != null) {
  93349. this._enableTeleportationOnController(this.leftController);
  93350. }
  93351. if (this.rightController != null) {
  93352. this._enableTeleportationOnController(this.rightController);
  93353. }
  93354. // Creates an image processing post process for the vignette not relying
  93355. // on the main scene configuration for image processing to reduce setup and spaces
  93356. // (gamma/linear) conflicts.
  93357. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  93358. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  93359. imageProcessingConfiguration.vignetteEnabled = true;
  93360. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  93361. this._webVRCamera.detachPostProcess(this._postProcessMove);
  93362. this._teleportationInitialized = true;
  93363. if (this._isDefaultTeleportationTarget) {
  93364. this._createTeleportationCircles();
  93365. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  93366. }
  93367. }
  93368. };
  93369. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  93370. var _this = this;
  93371. var controllerMesh = controller.webVRController.mesh;
  93372. if (controllerMesh) {
  93373. controller._interactionsEnabled = true;
  93374. controller._activatePointer();
  93375. if (this.webVROptions.laserToggle) {
  93376. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  93377. // Enabling / disabling laserPointer
  93378. if (_this._displayLaserPointer && stateObject.value === 1) {
  93379. if (controller._activePointer) {
  93380. controller._deactivatePointer();
  93381. }
  93382. else {
  93383. controller._activatePointer();
  93384. }
  93385. if (_this.displayGaze) {
  93386. controller._gazeTracker.isVisible = controller._activePointer;
  93387. }
  93388. }
  93389. });
  93390. }
  93391. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  93392. var gazer = controller;
  93393. if (_this._noControllerIsActive) {
  93394. gazer = _this._cameraGazer;
  93395. }
  93396. if (!gazer._pointerDownOnMeshAsked) {
  93397. if (stateObject.value > _this._padSensibilityUp) {
  93398. gazer._selectionPointerDown();
  93399. }
  93400. }
  93401. else if (stateObject.value < _this._padSensibilityDown) {
  93402. gazer._selectionPointerUp();
  93403. }
  93404. });
  93405. }
  93406. };
  93407. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93408. // Dont teleport if another gaze already requested teleportation
  93409. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93410. return;
  93411. }
  93412. if (!gazer._teleportationRequestInitiated) {
  93413. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93414. gazer._activatePointer();
  93415. gazer._teleportationRequestInitiated = true;
  93416. }
  93417. }
  93418. else {
  93419. // Listening to the proper controller values changes to confirm teleportation
  93420. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93421. if (this._teleportActive) {
  93422. this._teleportCamera(this._haloCenter);
  93423. }
  93424. gazer._teleportationRequestInitiated = false;
  93425. }
  93426. }
  93427. };
  93428. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93429. // Only rotate when user is not currently selecting a teleportation location
  93430. if (gazer._teleportationRequestInitiated) {
  93431. return;
  93432. }
  93433. if (!gazer._rotationLeftAsked) {
  93434. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93435. gazer._rotationLeftAsked = true;
  93436. if (this._rotationAllowed) {
  93437. this._rotateCamera(false);
  93438. }
  93439. }
  93440. }
  93441. else {
  93442. if (stateObject.x > -this._padSensibilityDown) {
  93443. gazer._rotationLeftAsked = false;
  93444. }
  93445. }
  93446. if (!gazer._rotationRightAsked) {
  93447. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93448. gazer._rotationRightAsked = true;
  93449. if (this._rotationAllowed) {
  93450. this._rotateCamera(true);
  93451. }
  93452. }
  93453. }
  93454. else {
  93455. if (stateObject.x < this._padSensibilityDown) {
  93456. gazer._rotationRightAsked = false;
  93457. }
  93458. }
  93459. };
  93460. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93461. // Only teleport backwards when user is not currently selecting a teleportation location
  93462. if (gazer._teleportationRequestInitiated) {
  93463. return;
  93464. }
  93465. // Teleport backwards
  93466. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93467. if (!gazer._teleportationBackRequestInitiated) {
  93468. if (!this.currentVRCamera) {
  93469. return;
  93470. }
  93471. // Get rotation and position of the current camera
  93472. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93473. var position = this.currentVRCamera.position;
  93474. // If the camera has device position, use that instead
  93475. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93476. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93477. position = this.currentVRCamera.devicePosition;
  93478. }
  93479. // Get matrix with only the y rotation of the device rotation
  93480. rotation.toEulerAnglesToRef(this._workingVector);
  93481. this._workingVector.z = 0;
  93482. this._workingVector.x = 0;
  93483. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93484. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93485. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93486. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93487. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93488. var ray = new BABYLON.Ray(position, this._workingVector);
  93489. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93490. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93491. this._teleportCamera(hit.pickedPoint);
  93492. }
  93493. gazer._teleportationBackRequestInitiated = true;
  93494. }
  93495. }
  93496. else {
  93497. gazer._teleportationBackRequestInitiated = false;
  93498. }
  93499. };
  93500. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93501. var _this = this;
  93502. var controllerMesh = controller.webVRController.mesh;
  93503. if (controllerMesh) {
  93504. if (!controller._interactionsEnabled) {
  93505. this._enableInteractionOnController(controller);
  93506. }
  93507. controller._interactionsEnabled = true;
  93508. controller._teleportationEnabled = true;
  93509. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93510. controller._dpadPressed = false;
  93511. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93512. controller._dpadPressed = stateObject.pressed;
  93513. if (!controller._dpadPressed) {
  93514. controller._rotationLeftAsked = false;
  93515. controller._rotationRightAsked = false;
  93516. controller._teleportationBackRequestInitiated = false;
  93517. }
  93518. });
  93519. }
  93520. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93521. if (_this.teleportationEnabled) {
  93522. _this._checkTeleportBackwards(stateObject, controller);
  93523. _this._checkTeleportWithRay(stateObject, controller);
  93524. }
  93525. _this._checkRotate(stateObject, controller);
  93526. });
  93527. }
  93528. };
  93529. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93530. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93531. this._teleportationTarget.isPickable = false;
  93532. var length = 512;
  93533. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93534. dynamicTexture.hasAlpha = true;
  93535. var context = dynamicTexture.getContext();
  93536. var centerX = length / 2;
  93537. var centerY = length / 2;
  93538. var radius = 200;
  93539. context.beginPath();
  93540. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93541. context.fillStyle = this._teleportationFillColor;
  93542. context.fill();
  93543. context.lineWidth = 10;
  93544. context.strokeStyle = this._teleportationBorderColor;
  93545. context.stroke();
  93546. context.closePath();
  93547. dynamicTexture.update();
  93548. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93549. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93550. this._teleportationTarget.material = teleportationCircleMaterial;
  93551. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93552. torus.isPickable = false;
  93553. torus.parent = this._teleportationTarget;
  93554. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93555. var keys = [];
  93556. keys.push({
  93557. frame: 0,
  93558. value: 0
  93559. });
  93560. keys.push({
  93561. frame: 30,
  93562. value: 0.4
  93563. });
  93564. keys.push({
  93565. frame: 60,
  93566. value: 0
  93567. });
  93568. animationInnerCircle.setKeys(keys);
  93569. var easingFunction = new BABYLON.SineEase();
  93570. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93571. animationInnerCircle.setEasingFunction(easingFunction);
  93572. torus.animations = [];
  93573. torus.animations.push(animationInnerCircle);
  93574. this._scene.beginAnimation(torus, 0, 60, true);
  93575. this._hideTeleportationTarget();
  93576. };
  93577. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93578. this._teleportActive = true;
  93579. if (this._teleportationInitialized) {
  93580. this._teleportationTarget.isVisible = true;
  93581. if (this._isDefaultTeleportationTarget) {
  93582. this._teleportationTarget.getChildren()[0].isVisible = true;
  93583. }
  93584. }
  93585. };
  93586. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93587. this._teleportActive = false;
  93588. if (this._teleportationInitialized) {
  93589. this._teleportationTarget.isVisible = false;
  93590. if (this._isDefaultTeleportationTarget) {
  93591. this._teleportationTarget.getChildren()[0].isVisible = false;
  93592. }
  93593. }
  93594. };
  93595. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93596. var _this = this;
  93597. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93598. return;
  93599. }
  93600. if (right) {
  93601. this._rotationAngle++;
  93602. }
  93603. else {
  93604. this._rotationAngle--;
  93605. }
  93606. this.currentVRCamera.animations = [];
  93607. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93608. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93609. var animationRotationKeys = [];
  93610. animationRotationKeys.push({
  93611. frame: 0,
  93612. value: this.currentVRCamera.rotationQuaternion
  93613. });
  93614. animationRotationKeys.push({
  93615. frame: 6,
  93616. value: target
  93617. });
  93618. animationRotation.setKeys(animationRotationKeys);
  93619. animationRotation.setEasingFunction(this._circleEase);
  93620. this.currentVRCamera.animations.push(animationRotation);
  93621. this._postProcessMove.animations = [];
  93622. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93623. var vignetteWeightKeys = [];
  93624. vignetteWeightKeys.push({
  93625. frame: 0,
  93626. value: 0
  93627. });
  93628. vignetteWeightKeys.push({
  93629. frame: 3,
  93630. value: 4
  93631. });
  93632. vignetteWeightKeys.push({
  93633. frame: 6,
  93634. value: 0
  93635. });
  93636. animationPP.setKeys(vignetteWeightKeys);
  93637. animationPP.setEasingFunction(this._circleEase);
  93638. this._postProcessMove.animations.push(animationPP);
  93639. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93640. var vignetteStretchKeys = [];
  93641. vignetteStretchKeys.push({
  93642. frame: 0,
  93643. value: 0
  93644. });
  93645. vignetteStretchKeys.push({
  93646. frame: 3,
  93647. value: 10
  93648. });
  93649. vignetteStretchKeys.push({
  93650. frame: 6,
  93651. value: 0
  93652. });
  93653. animationPP2.setKeys(vignetteStretchKeys);
  93654. animationPP2.setEasingFunction(this._circleEase);
  93655. this._postProcessMove.animations.push(animationPP2);
  93656. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93657. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93658. this._postProcessMove.samples = 4;
  93659. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93660. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93661. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93662. });
  93663. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93664. };
  93665. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93666. if (hit.pickedPoint) {
  93667. if (gazer._teleportationRequestInitiated) {
  93668. this._displayTeleportationTarget();
  93669. this._haloCenter.copyFrom(hit.pickedPoint);
  93670. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93671. }
  93672. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93673. if (pickNormal) {
  93674. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93675. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93676. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93677. }
  93678. this._teleportationTarget.position.y += 0.1;
  93679. }
  93680. };
  93681. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93682. var _this = this;
  93683. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93684. return;
  93685. }
  93686. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93687. // offset of the headset from the anchor.
  93688. if (this.webVRCamera.leftCamera) {
  93689. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93690. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93691. location.subtractToRef(this._workingVector, this._workingVector);
  93692. }
  93693. else {
  93694. this._workingVector.copyFrom(location);
  93695. }
  93696. // Add height to account for user's height offset
  93697. if (this.isInVRMode) {
  93698. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93699. }
  93700. else {
  93701. this._workingVector.y += this._defaultHeight;
  93702. }
  93703. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93704. // Create animation from the camera's position to the new location
  93705. this.currentVRCamera.animations = [];
  93706. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93707. var animationCameraTeleportationKeys = [{
  93708. frame: 0,
  93709. value: this.currentVRCamera.position
  93710. },
  93711. {
  93712. frame: 11,
  93713. value: this._workingVector
  93714. }
  93715. ];
  93716. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93717. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93718. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93719. this._postProcessMove.animations = [];
  93720. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93721. var vignetteWeightKeys = [];
  93722. vignetteWeightKeys.push({
  93723. frame: 0,
  93724. value: 0
  93725. });
  93726. vignetteWeightKeys.push({
  93727. frame: 5,
  93728. value: 8
  93729. });
  93730. vignetteWeightKeys.push({
  93731. frame: 11,
  93732. value: 0
  93733. });
  93734. animationPP.setKeys(vignetteWeightKeys);
  93735. this._postProcessMove.animations.push(animationPP);
  93736. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93737. var vignetteStretchKeys = [];
  93738. vignetteStretchKeys.push({
  93739. frame: 0,
  93740. value: 0
  93741. });
  93742. vignetteStretchKeys.push({
  93743. frame: 5,
  93744. value: 10
  93745. });
  93746. vignetteStretchKeys.push({
  93747. frame: 11,
  93748. value: 0
  93749. });
  93750. animationPP2.setKeys(vignetteStretchKeys);
  93751. this._postProcessMove.animations.push(animationPP2);
  93752. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93753. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93754. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93755. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93756. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93757. });
  93758. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93759. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93760. });
  93761. this._hideTeleportationTarget();
  93762. };
  93763. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93764. if (normal) {
  93765. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93766. if (angle < Math.PI / 2) {
  93767. normal.scaleInPlace(-1);
  93768. }
  93769. }
  93770. return normal;
  93771. };
  93772. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93773. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93774. return;
  93775. }
  93776. var ray = gazer._getForwardRay(this._rayLength);
  93777. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93778. if (hit) {
  93779. // Populate the contrllers mesh that can be used for drag/drop
  93780. if (gazer._laserPointer) {
  93781. hit.originMesh = gazer._laserPointer.parent;
  93782. }
  93783. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93784. }
  93785. gazer._currentHit = hit;
  93786. // Moving the gazeTracker on the mesh face targetted
  93787. if (hit && hit.pickedPoint) {
  93788. if (this._displayGaze) {
  93789. var multiplier = 1;
  93790. gazer._gazeTracker.isVisible = true;
  93791. if (gazer._isActionableMesh) {
  93792. multiplier = 3;
  93793. }
  93794. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93795. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93796. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93797. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93798. // To avoid z-fighting
  93799. var deltaFighting = 0.002;
  93800. if (pickNormal) {
  93801. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93802. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93803. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93804. }
  93805. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93806. if (gazer._gazeTracker.position.x < 0) {
  93807. gazer._gazeTracker.position.x += deltaFighting;
  93808. }
  93809. else {
  93810. gazer._gazeTracker.position.x -= deltaFighting;
  93811. }
  93812. if (gazer._gazeTracker.position.y < 0) {
  93813. gazer._gazeTracker.position.y += deltaFighting;
  93814. }
  93815. else {
  93816. gazer._gazeTracker.position.y -= deltaFighting;
  93817. }
  93818. if (gazer._gazeTracker.position.z < 0) {
  93819. gazer._gazeTracker.position.z += deltaFighting;
  93820. }
  93821. else {
  93822. gazer._gazeTracker.position.z -= deltaFighting;
  93823. }
  93824. }
  93825. // Changing the size of the laser pointer based on the distance from the targetted point
  93826. gazer._updatePointerDistance(hit.distance);
  93827. }
  93828. else {
  93829. gazer._updatePointerDistance();
  93830. gazer._gazeTracker.isVisible = false;
  93831. }
  93832. if (hit && hit.pickedMesh) {
  93833. // The object selected is the floor, we're in a teleportation scenario
  93834. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93835. // Moving the teleportation area to this targetted point
  93836. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93837. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93838. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93839. }
  93840. gazer._currentMeshSelected = null;
  93841. if (gazer._teleportationRequestInitiated) {
  93842. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93843. }
  93844. return;
  93845. }
  93846. // If not, we're in a selection scenario
  93847. //this._teleportationAllowed = false;
  93848. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93849. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93850. this.onNewMeshPicked.notifyObservers(hit);
  93851. gazer._currentMeshSelected = hit.pickedMesh;
  93852. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93853. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93854. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93855. gazer._isActionableMesh = true;
  93856. }
  93857. else {
  93858. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93859. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93860. gazer._isActionableMesh = false;
  93861. }
  93862. try {
  93863. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93864. }
  93865. catch (err) {
  93866. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93867. }
  93868. }
  93869. else {
  93870. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93871. gazer._currentMeshSelected = null;
  93872. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93873. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93874. }
  93875. }
  93876. }
  93877. else {
  93878. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93879. gazer._currentMeshSelected = null;
  93880. //this._teleportationAllowed = false;
  93881. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93882. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93883. }
  93884. };
  93885. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93886. if (mesh) {
  93887. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93888. }
  93889. };
  93890. /**
  93891. * Sets the color of the laser ray from the vr controllers.
  93892. * @param color new color for the ray.
  93893. */
  93894. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93895. if (this.leftController) {
  93896. this.leftController._setLaserPointerColor(color);
  93897. }
  93898. if (this.rightController) {
  93899. this.rightController._setLaserPointerColor(color);
  93900. }
  93901. };
  93902. /**
  93903. * Sets the color of the ray from the vr headsets gaze.
  93904. * @param color new color for the ray.
  93905. */
  93906. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93907. if (!this._cameraGazer._gazeTracker.material) {
  93908. return;
  93909. }
  93910. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93911. if (this.leftController) {
  93912. this.leftController._gazeTracker.material.emissiveColor = color;
  93913. }
  93914. if (this.rightController) {
  93915. this.rightController._gazeTracker.material.emissiveColor = color;
  93916. }
  93917. };
  93918. /**
  93919. * Exits VR and disposes of the vr experience helper
  93920. */
  93921. VRExperienceHelper.prototype.dispose = function () {
  93922. if (this.isInVRMode) {
  93923. this.exitVR();
  93924. }
  93925. if (this._postProcessMove) {
  93926. this._postProcessMove.dispose();
  93927. }
  93928. if (this._webVRCamera) {
  93929. this._webVRCamera.dispose();
  93930. }
  93931. if (this._vrDeviceOrientationCamera) {
  93932. this._vrDeviceOrientationCamera.dispose();
  93933. }
  93934. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93935. document.body.removeChild(this._btnVR);
  93936. }
  93937. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93938. this._deviceOrientationCamera.dispose();
  93939. }
  93940. if (this._cameraGazer) {
  93941. this._cameraGazer.dispose();
  93942. }
  93943. if (this.leftController) {
  93944. this.leftController.dispose();
  93945. }
  93946. if (this.rightController) {
  93947. this.rightController.dispose();
  93948. }
  93949. if (this._teleportationTarget) {
  93950. this._teleportationTarget.dispose();
  93951. }
  93952. this._floorMeshesCollection = [];
  93953. document.removeEventListener("keydown", this._onKeyDown);
  93954. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93955. window.removeEventListener("resize", this._onResize);
  93956. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93957. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93958. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93959. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93960. document.onmsfullscreenchange = null;
  93961. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93962. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93963. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93964. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93965. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93966. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93967. this._scene.unregisterBeforeRender(this.beforeRender);
  93968. };
  93969. /**
  93970. * Gets the name of the VRExperienceHelper class
  93971. * @returns "VRExperienceHelper"
  93972. */
  93973. VRExperienceHelper.prototype.getClassName = function () {
  93974. return "VRExperienceHelper";
  93975. };
  93976. return VRExperienceHelper;
  93977. }());
  93978. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93979. })(BABYLON || (BABYLON = {}));
  93980. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93981. // Mainly based on these 2 articles :
  93982. // 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
  93983. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93984. var BABYLON;
  93985. (function (BABYLON) {
  93986. /**
  93987. * Defines the potential axis of a Joystick
  93988. */
  93989. var JoystickAxis;
  93990. (function (JoystickAxis) {
  93991. /** X axis */
  93992. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93993. /** Y axis */
  93994. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93995. /** Z axis */
  93996. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93997. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93998. /**
  93999. * Class used to define virtual joystick (used in touch mode)
  94000. */
  94001. var VirtualJoystick = /** @class */ (function () {
  94002. /**
  94003. * Creates a new virtual joystick
  94004. * @param leftJoystick defines that the joystick is for left hand (false by default)
  94005. */
  94006. function VirtualJoystick(leftJoystick) {
  94007. var _this = this;
  94008. if (leftJoystick) {
  94009. this._leftJoystick = true;
  94010. }
  94011. else {
  94012. this._leftJoystick = false;
  94013. }
  94014. VirtualJoystick._globalJoystickIndex++;
  94015. // By default left & right arrow keys are moving the X
  94016. // and up & down keys are moving the Y
  94017. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94018. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94019. this.reverseLeftRight = false;
  94020. this.reverseUpDown = false;
  94021. // collections of pointers
  94022. this._touches = new BABYLON.StringDictionary();
  94023. this.deltaPosition = BABYLON.Vector3.Zero();
  94024. this._joystickSensibility = 25;
  94025. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94026. this._onResize = function (evt) {
  94027. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94028. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94029. if (VirtualJoystick.vjCanvas) {
  94030. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  94031. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  94032. }
  94033. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  94034. };
  94035. // injecting a canvas element on top of the canvas 3D game
  94036. if (!VirtualJoystick.vjCanvas) {
  94037. window.addEventListener("resize", this._onResize, false);
  94038. VirtualJoystick.vjCanvas = document.createElement("canvas");
  94039. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  94040. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  94041. VirtualJoystick.vjCanvas.width = window.innerWidth;
  94042. VirtualJoystick.vjCanvas.height = window.innerHeight;
  94043. VirtualJoystick.vjCanvas.style.width = "100%";
  94044. VirtualJoystick.vjCanvas.style.height = "100%";
  94045. VirtualJoystick.vjCanvas.style.position = "absolute";
  94046. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  94047. VirtualJoystick.vjCanvas.style.top = "0px";
  94048. VirtualJoystick.vjCanvas.style.left = "0px";
  94049. VirtualJoystick.vjCanvas.style.zIndex = "5";
  94050. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  94051. // Support for jQuery PEP polyfill
  94052. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  94053. var context = VirtualJoystick.vjCanvas.getContext('2d');
  94054. if (!context) {
  94055. throw new Error("Unable to create canvas for virtual joystick");
  94056. }
  94057. VirtualJoystick.vjCanvasContext = context;
  94058. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  94059. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94060. document.body.appendChild(VirtualJoystick.vjCanvas);
  94061. }
  94062. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  94063. this.pressed = false;
  94064. // default joystick color
  94065. this._joystickColor = "cyan";
  94066. this._joystickPointerID = -1;
  94067. // current joystick position
  94068. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  94069. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  94070. // origin joystick position
  94071. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  94072. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  94073. this._onPointerDownHandlerRef = function (evt) {
  94074. _this._onPointerDown(evt);
  94075. };
  94076. this._onPointerMoveHandlerRef = function (evt) {
  94077. _this._onPointerMove(evt);
  94078. };
  94079. this._onPointerUpHandlerRef = function (evt) {
  94080. _this._onPointerUp(evt);
  94081. };
  94082. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  94083. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  94084. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  94085. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  94086. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  94087. evt.preventDefault(); // Disables system menu
  94088. }, false);
  94089. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94090. }
  94091. /**
  94092. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  94093. * @param newJoystickSensibility defines the new sensibility
  94094. */
  94095. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  94096. this._joystickSensibility = newJoystickSensibility;
  94097. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  94098. };
  94099. VirtualJoystick.prototype._onPointerDown = function (e) {
  94100. var positionOnScreenCondition;
  94101. e.preventDefault();
  94102. if (this._leftJoystick === true) {
  94103. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  94104. }
  94105. else {
  94106. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  94107. }
  94108. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  94109. // First contact will be dedicated to the virtual joystick
  94110. this._joystickPointerID = e.pointerId;
  94111. this._joystickPointerStartPos.x = e.clientX;
  94112. this._joystickPointerStartPos.y = e.clientY;
  94113. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  94114. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  94115. this._deltaJoystickVector.x = 0;
  94116. this._deltaJoystickVector.y = 0;
  94117. this.pressed = true;
  94118. this._touches.add(e.pointerId.toString(), e);
  94119. }
  94120. else {
  94121. // You can only trigger the action buttons with a joystick declared
  94122. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  94123. this._action();
  94124. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  94125. }
  94126. }
  94127. };
  94128. VirtualJoystick.prototype._onPointerMove = function (e) {
  94129. // If the current pointer is the one associated to the joystick (first touch contact)
  94130. if (this._joystickPointerID == e.pointerId) {
  94131. this._joystickPointerPos.x = e.clientX;
  94132. this._joystickPointerPos.y = e.clientY;
  94133. this._deltaJoystickVector = this._joystickPointerPos.clone();
  94134. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  94135. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  94136. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  94137. switch (this._axisTargetedByLeftAndRight) {
  94138. case JoystickAxis.X:
  94139. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  94140. break;
  94141. case JoystickAxis.Y:
  94142. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  94143. break;
  94144. case JoystickAxis.Z:
  94145. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  94146. break;
  94147. }
  94148. var directionUpDown = this.reverseUpDown ? 1 : -1;
  94149. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  94150. switch (this._axisTargetedByUpAndDown) {
  94151. case JoystickAxis.X:
  94152. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  94153. break;
  94154. case JoystickAxis.Y:
  94155. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  94156. break;
  94157. case JoystickAxis.Z:
  94158. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  94159. break;
  94160. }
  94161. }
  94162. else {
  94163. var data = this._touches.get(e.pointerId.toString());
  94164. if (data) {
  94165. data.x = e.clientX;
  94166. data.y = e.clientY;
  94167. }
  94168. }
  94169. };
  94170. VirtualJoystick.prototype._onPointerUp = function (e) {
  94171. if (this._joystickPointerID == e.pointerId) {
  94172. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  94173. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  94174. this._joystickPointerID = -1;
  94175. this.pressed = false;
  94176. }
  94177. else {
  94178. var touch = this._touches.get(e.pointerId.toString());
  94179. if (touch) {
  94180. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94181. }
  94182. }
  94183. this._deltaJoystickVector.x = 0;
  94184. this._deltaJoystickVector.y = 0;
  94185. this._touches.remove(e.pointerId.toString());
  94186. };
  94187. /**
  94188. * Change the color of the virtual joystick
  94189. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  94190. */
  94191. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  94192. this._joystickColor = newColor;
  94193. };
  94194. /**
  94195. * Defines a callback to call when the joystick is touched
  94196. * @param action defines the callback
  94197. */
  94198. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  94199. this._action = action;
  94200. };
  94201. /**
  94202. * Defines which axis you'd like to control for left & right
  94203. * @param axis defines the axis to use
  94204. */
  94205. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  94206. switch (axis) {
  94207. case JoystickAxis.X:
  94208. case JoystickAxis.Y:
  94209. case JoystickAxis.Z:
  94210. this._axisTargetedByLeftAndRight = axis;
  94211. break;
  94212. default:
  94213. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  94214. break;
  94215. }
  94216. };
  94217. /**
  94218. * Defines which axis you'd like to control for up & down
  94219. * @param axis defines the axis to use
  94220. */
  94221. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  94222. switch (axis) {
  94223. case JoystickAxis.X:
  94224. case JoystickAxis.Y:
  94225. case JoystickAxis.Z:
  94226. this._axisTargetedByUpAndDown = axis;
  94227. break;
  94228. default:
  94229. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  94230. break;
  94231. }
  94232. };
  94233. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  94234. var _this = this;
  94235. if (this.pressed) {
  94236. this._touches.forEach(function (key, touch) {
  94237. if (touch.pointerId === _this._joystickPointerID) {
  94238. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  94239. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  94240. VirtualJoystick.vjCanvasContext.beginPath();
  94241. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94242. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94243. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  94244. VirtualJoystick.vjCanvasContext.stroke();
  94245. VirtualJoystick.vjCanvasContext.closePath();
  94246. VirtualJoystick.vjCanvasContext.beginPath();
  94247. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94248. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  94249. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  94250. VirtualJoystick.vjCanvasContext.stroke();
  94251. VirtualJoystick.vjCanvasContext.closePath();
  94252. VirtualJoystick.vjCanvasContext.beginPath();
  94253. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  94254. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  94255. VirtualJoystick.vjCanvasContext.stroke();
  94256. VirtualJoystick.vjCanvasContext.closePath();
  94257. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  94258. }
  94259. else {
  94260. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  94261. VirtualJoystick.vjCanvasContext.beginPath();
  94262. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  94263. VirtualJoystick.vjCanvasContext.beginPath();
  94264. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  94265. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  94266. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  94267. VirtualJoystick.vjCanvasContext.stroke();
  94268. VirtualJoystick.vjCanvasContext.closePath();
  94269. touch.prevX = touch.x;
  94270. touch.prevY = touch.y;
  94271. }
  94272. ;
  94273. });
  94274. }
  94275. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  94276. };
  94277. /**
  94278. * Release internal HTML canvas
  94279. */
  94280. VirtualJoystick.prototype.releaseCanvas = function () {
  94281. if (VirtualJoystick.vjCanvas) {
  94282. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  94283. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  94284. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  94285. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  94286. window.removeEventListener("resize", this._onResize);
  94287. document.body.removeChild(VirtualJoystick.vjCanvas);
  94288. VirtualJoystick.vjCanvas = null;
  94289. }
  94290. };
  94291. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  94292. VirtualJoystick._globalJoystickIndex = 0;
  94293. return VirtualJoystick;
  94294. }());
  94295. BABYLON.VirtualJoystick = VirtualJoystick;
  94296. })(BABYLON || (BABYLON = {}));
  94297. //# sourceMappingURL=babylon.virtualJoystick.js.map
  94298. var BABYLON;
  94299. (function (BABYLON) {
  94300. // We're mainly based on the logic defined into the FreeCamera code
  94301. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  94302. __extends(VirtualJoysticksCamera, _super);
  94303. function VirtualJoysticksCamera(name, position, scene) {
  94304. var _this = _super.call(this, name, position, scene) || this;
  94305. _this.inputs.addVirtualJoystick();
  94306. return _this;
  94307. }
  94308. VirtualJoysticksCamera.prototype.getClassName = function () {
  94309. return "VirtualJoysticksCamera";
  94310. };
  94311. return VirtualJoysticksCamera;
  94312. }(BABYLON.FreeCamera));
  94313. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  94314. })(BABYLON || (BABYLON = {}));
  94315. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  94316. var BABYLON;
  94317. (function (BABYLON) {
  94318. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  94319. function FreeCameraVirtualJoystickInput() {
  94320. }
  94321. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  94322. return this._leftjoystick;
  94323. };
  94324. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  94325. return this._rightjoystick;
  94326. };
  94327. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  94328. if (this._leftjoystick) {
  94329. var camera = this.camera;
  94330. var speed = camera._computeLocalCameraSpeed() * 50;
  94331. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  94332. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  94333. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  94334. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  94335. if (!this._leftjoystick.pressed) {
  94336. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  94337. }
  94338. if (!this._rightjoystick.pressed) {
  94339. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  94340. }
  94341. }
  94342. };
  94343. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  94344. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  94345. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  94346. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  94347. this._leftjoystick.setJoystickSensibility(0.15);
  94348. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  94349. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  94350. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  94351. this._rightjoystick.reverseUpDown = true;
  94352. this._rightjoystick.setJoystickSensibility(0.05);
  94353. this._rightjoystick.setJoystickColor("yellow");
  94354. };
  94355. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  94356. this._leftjoystick.releaseCanvas();
  94357. this._rightjoystick.releaseCanvas();
  94358. };
  94359. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  94360. return "FreeCameraVirtualJoystickInput";
  94361. };
  94362. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  94363. return "virtualJoystick";
  94364. };
  94365. return FreeCameraVirtualJoystickInput;
  94366. }());
  94367. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  94368. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  94369. })(BABYLON || (BABYLON = {}));
  94370. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  94371. var BABYLON;
  94372. (function (BABYLON) {
  94373. var SimplificationSettings = /** @class */ (function () {
  94374. function SimplificationSettings(quality, distance, optimizeMesh) {
  94375. this.quality = quality;
  94376. this.distance = distance;
  94377. this.optimizeMesh = optimizeMesh;
  94378. }
  94379. return SimplificationSettings;
  94380. }());
  94381. BABYLON.SimplificationSettings = SimplificationSettings;
  94382. var SimplificationQueue = /** @class */ (function () {
  94383. function SimplificationQueue() {
  94384. this.running = false;
  94385. this._simplificationArray = [];
  94386. }
  94387. SimplificationQueue.prototype.addTask = function (task) {
  94388. this._simplificationArray.push(task);
  94389. };
  94390. SimplificationQueue.prototype.executeNext = function () {
  94391. var task = this._simplificationArray.pop();
  94392. if (task) {
  94393. this.running = true;
  94394. this.runSimplification(task);
  94395. }
  94396. else {
  94397. this.running = false;
  94398. }
  94399. };
  94400. SimplificationQueue.prototype.runSimplification = function (task) {
  94401. var _this = this;
  94402. if (task.parallelProcessing) {
  94403. //parallel simplifier
  94404. task.settings.forEach(function (setting) {
  94405. var simplifier = _this.getSimplifier(task);
  94406. simplifier.simplify(setting, function (newMesh) {
  94407. task.mesh.addLODLevel(setting.distance, newMesh);
  94408. newMesh.isVisible = true;
  94409. //check if it is the last
  94410. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94411. //all done, run the success callback.
  94412. task.successCallback();
  94413. }
  94414. _this.executeNext();
  94415. });
  94416. });
  94417. }
  94418. else {
  94419. //single simplifier.
  94420. var simplifier = this.getSimplifier(task);
  94421. var runDecimation = function (setting, callback) {
  94422. simplifier.simplify(setting, function (newMesh) {
  94423. task.mesh.addLODLevel(setting.distance, newMesh);
  94424. newMesh.isVisible = true;
  94425. //run the next quality level
  94426. callback();
  94427. });
  94428. };
  94429. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94430. runDecimation(task.settings[loop.index], function () {
  94431. loop.executeNext();
  94432. });
  94433. }, function () {
  94434. //execution ended, run the success callback.
  94435. if (task.successCallback) {
  94436. task.successCallback();
  94437. }
  94438. _this.executeNext();
  94439. });
  94440. }
  94441. };
  94442. SimplificationQueue.prototype.getSimplifier = function (task) {
  94443. switch (task.simplificationType) {
  94444. case SimplificationType.QUADRATIC:
  94445. default:
  94446. return new QuadraticErrorSimplification(task.mesh);
  94447. }
  94448. };
  94449. return SimplificationQueue;
  94450. }());
  94451. BABYLON.SimplificationQueue = SimplificationQueue;
  94452. /**
  94453. * The implemented types of simplification
  94454. * At the moment only Quadratic Error Decimation is implemented
  94455. */
  94456. var SimplificationType;
  94457. (function (SimplificationType) {
  94458. /** Quadratic error decimation */
  94459. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94460. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94461. var DecimationTriangle = /** @class */ (function () {
  94462. function DecimationTriangle(vertices) {
  94463. this.vertices = vertices;
  94464. this.error = new Array(4);
  94465. this.deleted = false;
  94466. this.isDirty = false;
  94467. this.deletePending = false;
  94468. this.borderFactor = 0;
  94469. }
  94470. return DecimationTriangle;
  94471. }());
  94472. BABYLON.DecimationTriangle = DecimationTriangle;
  94473. var DecimationVertex = /** @class */ (function () {
  94474. function DecimationVertex(position, id) {
  94475. this.position = position;
  94476. this.id = id;
  94477. this.isBorder = true;
  94478. this.q = new QuadraticMatrix();
  94479. this.triangleCount = 0;
  94480. this.triangleStart = 0;
  94481. this.originalOffsets = [];
  94482. }
  94483. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94484. this.position.copyFrom(newPosition);
  94485. };
  94486. return DecimationVertex;
  94487. }());
  94488. BABYLON.DecimationVertex = DecimationVertex;
  94489. var QuadraticMatrix = /** @class */ (function () {
  94490. function QuadraticMatrix(data) {
  94491. this.data = new Array(10);
  94492. for (var i = 0; i < 10; ++i) {
  94493. if (data && data[i]) {
  94494. this.data[i] = data[i];
  94495. }
  94496. else {
  94497. this.data[i] = 0;
  94498. }
  94499. }
  94500. }
  94501. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94502. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94503. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94504. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94505. return det;
  94506. };
  94507. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94508. for (var i = 0; i < 10; ++i) {
  94509. this.data[i] += matrix.data[i];
  94510. }
  94511. };
  94512. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94513. for (var i = 0; i < 10; ++i) {
  94514. this.data[i] += data[i];
  94515. }
  94516. };
  94517. QuadraticMatrix.prototype.add = function (matrix) {
  94518. var m = new QuadraticMatrix();
  94519. for (var i = 0; i < 10; ++i) {
  94520. m.data[i] = this.data[i] + matrix.data[i];
  94521. }
  94522. return m;
  94523. };
  94524. QuadraticMatrix.FromData = function (a, b, c, d) {
  94525. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94526. };
  94527. //returning an array to avoid garbage collection
  94528. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94529. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94530. };
  94531. return QuadraticMatrix;
  94532. }());
  94533. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94534. var Reference = /** @class */ (function () {
  94535. function Reference(vertexId, triangleId) {
  94536. this.vertexId = vertexId;
  94537. this.triangleId = triangleId;
  94538. }
  94539. return Reference;
  94540. }());
  94541. BABYLON.Reference = Reference;
  94542. /**
  94543. * An implementation of the Quadratic Error simplification algorithm.
  94544. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94545. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94546. * @author RaananW
  94547. */
  94548. var QuadraticErrorSimplification = /** @class */ (function () {
  94549. function QuadraticErrorSimplification(_mesh) {
  94550. this._mesh = _mesh;
  94551. this.syncIterations = 5000;
  94552. this.aggressiveness = 7;
  94553. this.decimationIterations = 100;
  94554. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94555. }
  94556. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94557. var _this = this;
  94558. this.initDecimatedMesh();
  94559. //iterating through the submeshes array, one after the other.
  94560. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94561. _this.initWithMesh(loop.index, function () {
  94562. _this.runDecimation(settings, loop.index, function () {
  94563. loop.executeNext();
  94564. });
  94565. }, settings.optimizeMesh);
  94566. }, function () {
  94567. setTimeout(function () {
  94568. successCallback(_this._reconstructedMesh);
  94569. }, 0);
  94570. });
  94571. };
  94572. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94573. var _this = this;
  94574. var targetCount = ~~(this.triangles.length * settings.quality);
  94575. var deletedTriangles = 0;
  94576. var triangleCount = this.triangles.length;
  94577. var iterationFunction = function (iteration, callback) {
  94578. setTimeout(function () {
  94579. if (iteration % 5 === 0) {
  94580. _this.updateMesh(iteration === 0);
  94581. }
  94582. for (var i = 0; i < _this.triangles.length; ++i) {
  94583. _this.triangles[i].isDirty = false;
  94584. }
  94585. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94586. var trianglesIterator = function (i) {
  94587. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94588. var t = _this.triangles[tIdx];
  94589. if (!t)
  94590. return;
  94591. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94592. return;
  94593. }
  94594. for (var j = 0; j < 3; ++j) {
  94595. if (t.error[j] < threshold) {
  94596. var deleted0 = [];
  94597. var deleted1 = [];
  94598. var v0 = t.vertices[j];
  94599. var v1 = t.vertices[(j + 1) % 3];
  94600. if (v0.isBorder || v1.isBorder)
  94601. continue;
  94602. var p = BABYLON.Vector3.Zero();
  94603. var n = BABYLON.Vector3.Zero();
  94604. var uv = BABYLON.Vector2.Zero();
  94605. var color = new BABYLON.Color4(0, 0, 0, 1);
  94606. _this.calculateError(v0, v1, p, n, uv, color);
  94607. var delTr = new Array();
  94608. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94609. continue;
  94610. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94611. continue;
  94612. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94613. continue;
  94614. var uniqueArray = new Array();
  94615. delTr.forEach(function (deletedT) {
  94616. if (uniqueArray.indexOf(deletedT) === -1) {
  94617. deletedT.deletePending = true;
  94618. uniqueArray.push(deletedT);
  94619. }
  94620. });
  94621. if (uniqueArray.length % 2 !== 0) {
  94622. continue;
  94623. }
  94624. v0.q = v1.q.add(v0.q);
  94625. v0.updatePosition(p);
  94626. var tStart = _this.references.length;
  94627. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94628. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94629. var tCount = _this.references.length - tStart;
  94630. if (tCount <= v0.triangleCount) {
  94631. if (tCount) {
  94632. for (var c = 0; c < tCount; c++) {
  94633. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94634. }
  94635. }
  94636. }
  94637. else {
  94638. v0.triangleStart = tStart;
  94639. }
  94640. v0.triangleCount = tCount;
  94641. break;
  94642. }
  94643. }
  94644. };
  94645. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94646. }, 0);
  94647. };
  94648. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94649. if (triangleCount - deletedTriangles <= targetCount)
  94650. loop.breakLoop();
  94651. else {
  94652. iterationFunction(loop.index, function () {
  94653. loop.executeNext();
  94654. });
  94655. }
  94656. }, function () {
  94657. setTimeout(function () {
  94658. //reconstruct this part of the mesh
  94659. _this.reconstructMesh(submeshIndex);
  94660. successCallback();
  94661. }, 0);
  94662. });
  94663. };
  94664. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94665. var _this = this;
  94666. this.vertices = [];
  94667. this.triangles = [];
  94668. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94669. var indices = this._mesh.getIndices();
  94670. var submesh = this._mesh.subMeshes[submeshIndex];
  94671. var findInVertices = function (positionToSearch) {
  94672. if (optimizeMesh) {
  94673. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94674. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94675. return _this.vertices[ii];
  94676. }
  94677. }
  94678. }
  94679. return null;
  94680. };
  94681. var vertexReferences = [];
  94682. var vertexInit = function (i) {
  94683. if (!positionData) {
  94684. return;
  94685. }
  94686. var offset = i + submesh.verticesStart;
  94687. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94688. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94689. vertex.originalOffsets.push(offset);
  94690. if (vertex.id === _this.vertices.length) {
  94691. _this.vertices.push(vertex);
  94692. }
  94693. vertexReferences.push(vertex.id);
  94694. };
  94695. //var totalVertices = mesh.getTotalVertices();
  94696. var totalVertices = submesh.verticesCount;
  94697. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94698. var indicesInit = function (i) {
  94699. if (!indices) {
  94700. return;
  94701. }
  94702. var offset = (submesh.indexStart / 3) + i;
  94703. var pos = (offset * 3);
  94704. var i0 = indices[pos + 0];
  94705. var i1 = indices[pos + 1];
  94706. var i2 = indices[pos + 2];
  94707. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94708. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94709. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94710. var triangle = new DecimationTriangle([v0, v1, v2]);
  94711. triangle.originalOffset = pos;
  94712. _this.triangles.push(triangle);
  94713. };
  94714. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94715. _this.init(callback);
  94716. });
  94717. });
  94718. };
  94719. QuadraticErrorSimplification.prototype.init = function (callback) {
  94720. var _this = this;
  94721. var triangleInit1 = function (i) {
  94722. var t = _this.triangles[i];
  94723. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94724. for (var j = 0; j < 3; j++) {
  94725. 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))));
  94726. }
  94727. };
  94728. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94729. var triangleInit2 = function (i) {
  94730. var t = _this.triangles[i];
  94731. for (var j = 0; j < 3; ++j) {
  94732. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94733. }
  94734. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94735. };
  94736. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94737. callback();
  94738. });
  94739. });
  94740. };
  94741. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94742. var newTriangles = [];
  94743. var i;
  94744. for (i = 0; i < this.vertices.length; ++i) {
  94745. this.vertices[i].triangleCount = 0;
  94746. }
  94747. var t;
  94748. var j;
  94749. for (i = 0; i < this.triangles.length; ++i) {
  94750. if (!this.triangles[i].deleted) {
  94751. t = this.triangles[i];
  94752. for (j = 0; j < 3; ++j) {
  94753. t.vertices[j].triangleCount = 1;
  94754. }
  94755. newTriangles.push(t);
  94756. }
  94757. }
  94758. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94759. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94760. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94761. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94762. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94763. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94764. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94765. var vertexCount = 0;
  94766. for (i = 0; i < this.vertices.length; ++i) {
  94767. var vertex = this.vertices[i];
  94768. vertex.id = vertexCount;
  94769. if (vertex.triangleCount) {
  94770. vertex.originalOffsets.forEach(function (originalOffset) {
  94771. if (!normalData) {
  94772. return;
  94773. }
  94774. newPositionData.push(vertex.position.x);
  94775. newPositionData.push(vertex.position.y);
  94776. newPositionData.push(vertex.position.z);
  94777. newNormalData.push(normalData[originalOffset * 3]);
  94778. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94779. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94780. if (uvs && uvs.length) {
  94781. newUVsData.push(uvs[(originalOffset * 2)]);
  94782. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94783. }
  94784. else if (colorsData && colorsData.length) {
  94785. newColorsData.push(colorsData[(originalOffset * 4)]);
  94786. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94787. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94788. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94789. }
  94790. ++vertexCount;
  94791. });
  94792. }
  94793. }
  94794. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94795. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94796. var submeshesArray = this._reconstructedMesh.subMeshes;
  94797. this._reconstructedMesh.subMeshes = [];
  94798. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94799. var originalIndices = this._mesh.getIndices();
  94800. for (i = 0; i < newTriangles.length; ++i) {
  94801. t = newTriangles[i]; //now get the new referencing point for each vertex
  94802. [0, 1, 2].forEach(function (idx) {
  94803. var id = originalIndices[t.originalOffset + idx];
  94804. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94805. if (offset < 0)
  94806. offset = 0;
  94807. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94808. });
  94809. }
  94810. //overwriting the old vertex buffers and indices.
  94811. this._reconstructedMesh.setIndices(newIndicesArray);
  94812. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94813. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94814. if (newUVsData.length > 0)
  94815. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94816. if (newColorsData.length > 0)
  94817. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94818. //create submesh
  94819. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94820. if (submeshIndex > 0) {
  94821. this._reconstructedMesh.subMeshes = [];
  94822. submeshesArray.forEach(function (submesh) {
  94823. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94824. });
  94825. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94826. }
  94827. };
  94828. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94829. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94830. this._reconstructedMesh.material = this._mesh.material;
  94831. this._reconstructedMesh.parent = this._mesh.parent;
  94832. this._reconstructedMesh.isVisible = false;
  94833. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94834. };
  94835. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94836. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94837. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94838. if (t.deleted)
  94839. continue;
  94840. var s = this.references[vertex1.triangleStart + i].vertexId;
  94841. var v1 = t.vertices[(s + 1) % 3];
  94842. var v2 = t.vertices[(s + 2) % 3];
  94843. if ((v1 === vertex2 || v2 === vertex2)) {
  94844. deletedArray[i] = true;
  94845. delTr.push(t);
  94846. continue;
  94847. }
  94848. var d1 = v1.position.subtract(point);
  94849. d1 = d1.normalize();
  94850. var d2 = v2.position.subtract(point);
  94851. d2 = d2.normalize();
  94852. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94853. return true;
  94854. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94855. deletedArray[i] = false;
  94856. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94857. return true;
  94858. }
  94859. return false;
  94860. };
  94861. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94862. var newDeleted = deletedTriangles;
  94863. for (var i = 0; i < vertex.triangleCount; ++i) {
  94864. var ref = this.references[vertex.triangleStart + i];
  94865. var t = this.triangles[ref.triangleId];
  94866. if (t.deleted)
  94867. continue;
  94868. if (deletedArray[i] && t.deletePending) {
  94869. t.deleted = true;
  94870. newDeleted++;
  94871. continue;
  94872. }
  94873. t.vertices[ref.vertexId] = origVertex;
  94874. t.isDirty = true;
  94875. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94876. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94877. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94878. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94879. this.references.push(ref);
  94880. }
  94881. return newDeleted;
  94882. };
  94883. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94884. for (var i = 0; i < this.vertices.length; ++i) {
  94885. var vCount = [];
  94886. var vId = [];
  94887. var v = this.vertices[i];
  94888. var j;
  94889. for (j = 0; j < v.triangleCount; ++j) {
  94890. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94891. for (var ii = 0; ii < 3; ii++) {
  94892. var ofs = 0;
  94893. var vv = triangle.vertices[ii];
  94894. while (ofs < vCount.length) {
  94895. if (vId[ofs] === vv.id)
  94896. break;
  94897. ++ofs;
  94898. }
  94899. if (ofs === vCount.length) {
  94900. vCount.push(1);
  94901. vId.push(vv.id);
  94902. }
  94903. else {
  94904. vCount[ofs]++;
  94905. }
  94906. }
  94907. }
  94908. for (j = 0; j < vCount.length; ++j) {
  94909. if (vCount[j] === 1) {
  94910. this.vertices[vId[j]].isBorder = true;
  94911. }
  94912. else {
  94913. this.vertices[vId[j]].isBorder = false;
  94914. }
  94915. }
  94916. }
  94917. };
  94918. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94919. if (identifyBorders === void 0) { identifyBorders = false; }
  94920. var i;
  94921. if (!identifyBorders) {
  94922. var newTrianglesVector = [];
  94923. for (i = 0; i < this.triangles.length; ++i) {
  94924. if (!this.triangles[i].deleted) {
  94925. newTrianglesVector.push(this.triangles[i]);
  94926. }
  94927. }
  94928. this.triangles = newTrianglesVector;
  94929. }
  94930. for (i = 0; i < this.vertices.length; ++i) {
  94931. this.vertices[i].triangleCount = 0;
  94932. this.vertices[i].triangleStart = 0;
  94933. }
  94934. var t;
  94935. var j;
  94936. var v;
  94937. for (i = 0; i < this.triangles.length; ++i) {
  94938. t = this.triangles[i];
  94939. for (j = 0; j < 3; ++j) {
  94940. v = t.vertices[j];
  94941. v.triangleCount++;
  94942. }
  94943. }
  94944. var tStart = 0;
  94945. for (i = 0; i < this.vertices.length; ++i) {
  94946. this.vertices[i].triangleStart = tStart;
  94947. tStart += this.vertices[i].triangleCount;
  94948. this.vertices[i].triangleCount = 0;
  94949. }
  94950. var newReferences = new Array(this.triangles.length * 3);
  94951. for (i = 0; i < this.triangles.length; ++i) {
  94952. t = this.triangles[i];
  94953. for (j = 0; j < 3; ++j) {
  94954. v = t.vertices[j];
  94955. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94956. v.triangleCount++;
  94957. }
  94958. }
  94959. this.references = newReferences;
  94960. if (identifyBorders) {
  94961. this.identifyBorder();
  94962. }
  94963. };
  94964. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94965. var x = point.x;
  94966. var y = point.y;
  94967. var z = point.z;
  94968. 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
  94969. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94970. };
  94971. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94972. var q = vertex1.q.add(vertex2.q);
  94973. var border = vertex1.isBorder && vertex2.isBorder;
  94974. var error = 0;
  94975. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94976. if (qDet !== 0 && !border) {
  94977. if (!pointResult) {
  94978. pointResult = BABYLON.Vector3.Zero();
  94979. }
  94980. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94981. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94982. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94983. error = this.vertexError(q, pointResult);
  94984. }
  94985. else {
  94986. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94987. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94988. var error1 = this.vertexError(q, vertex1.position);
  94989. var error2 = this.vertexError(q, vertex2.position);
  94990. var error3 = this.vertexError(q, p3);
  94991. error = Math.min(error1, error2, error3);
  94992. if (error === error1) {
  94993. if (pointResult) {
  94994. pointResult.copyFrom(vertex1.position);
  94995. }
  94996. }
  94997. else if (error === error2) {
  94998. if (pointResult) {
  94999. pointResult.copyFrom(vertex2.position);
  95000. }
  95001. }
  95002. else {
  95003. if (pointResult) {
  95004. pointResult.copyFrom(p3);
  95005. }
  95006. }
  95007. }
  95008. return error;
  95009. };
  95010. return QuadraticErrorSimplification;
  95011. }());
  95012. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  95013. })(BABYLON || (BABYLON = {}));
  95014. //# sourceMappingURL=babylon.meshSimplification.js.map
  95015. var BABYLON;
  95016. (function (BABYLON) {
  95017. var MeshLODLevel = /** @class */ (function () {
  95018. function MeshLODLevel(distance, mesh) {
  95019. this.distance = distance;
  95020. this.mesh = mesh;
  95021. }
  95022. return MeshLODLevel;
  95023. }());
  95024. BABYLON.MeshLODLevel = MeshLODLevel;
  95025. })(BABYLON || (BABYLON = {}));
  95026. //# sourceMappingURL=babylon.meshLODLevel.js.map
  95027. var BABYLON;
  95028. (function (BABYLON) {
  95029. /**
  95030. * Defines the root class used to create scene optimization to use with SceneOptimizer
  95031. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95032. */
  95033. var SceneOptimization = /** @class */ (function () {
  95034. /**
  95035. * Creates the SceneOptimization object
  95036. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95037. * @param desc defines the description associated with the optimization
  95038. */
  95039. function SceneOptimization(
  95040. /**
  95041. * Defines the priority of this optimization (0 by default which means first in the list)
  95042. */
  95043. priority) {
  95044. if (priority === void 0) { priority = 0; }
  95045. this.priority = priority;
  95046. }
  95047. /**
  95048. * Gets a string describing the action executed by the current optimization
  95049. * @returns description string
  95050. */
  95051. SceneOptimization.prototype.getDescription = function () {
  95052. return "";
  95053. };
  95054. /**
  95055. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95056. * @param scene defines the current scene where to apply this optimization
  95057. * @param optimizer defines the current optimizer
  95058. * @returns true if everything that can be done was applied
  95059. */
  95060. SceneOptimization.prototype.apply = function (scene, optimizer) {
  95061. return true;
  95062. };
  95063. ;
  95064. return SceneOptimization;
  95065. }());
  95066. BABYLON.SceneOptimization = SceneOptimization;
  95067. /**
  95068. * Defines an optimization used to reduce the size of render target textures
  95069. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95070. */
  95071. var TextureOptimization = /** @class */ (function (_super) {
  95072. __extends(TextureOptimization, _super);
  95073. /**
  95074. * Creates the TextureOptimization object
  95075. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95076. * @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
  95077. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95078. */
  95079. function TextureOptimization(
  95080. /**
  95081. * Defines the priority of this optimization (0 by default which means first in the list)
  95082. */
  95083. priority,
  95084. /**
  95085. * 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
  95086. */
  95087. maximumSize,
  95088. /**
  95089. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  95090. */
  95091. step) {
  95092. if (priority === void 0) { priority = 0; }
  95093. if (maximumSize === void 0) { maximumSize = 1024; }
  95094. if (step === void 0) { step = 0.5; }
  95095. var _this = _super.call(this, priority) || this;
  95096. _this.priority = priority;
  95097. _this.maximumSize = maximumSize;
  95098. _this.step = step;
  95099. return _this;
  95100. }
  95101. /**
  95102. * Gets a string describing the action executed by the current optimization
  95103. * @returns description string
  95104. */
  95105. TextureOptimization.prototype.getDescription = function () {
  95106. return "Reducing render target texture size to " + this.maximumSize;
  95107. };
  95108. /**
  95109. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95110. * @param scene defines the current scene where to apply this optimization
  95111. * @param optimizer defines the current optimizer
  95112. * @returns true if everything that can be done was applied
  95113. */
  95114. TextureOptimization.prototype.apply = function (scene, optimizer) {
  95115. var allDone = true;
  95116. for (var index = 0; index < scene.textures.length; index++) {
  95117. var texture = scene.textures[index];
  95118. if (!texture.canRescale || texture.getContext) {
  95119. continue;
  95120. }
  95121. var currentSize = texture.getSize();
  95122. var maxDimension = Math.max(currentSize.width, currentSize.height);
  95123. if (maxDimension > this.maximumSize) {
  95124. texture.scale(this.step);
  95125. allDone = false;
  95126. }
  95127. }
  95128. return allDone;
  95129. };
  95130. return TextureOptimization;
  95131. }(SceneOptimization));
  95132. BABYLON.TextureOptimization = TextureOptimization;
  95133. /**
  95134. * Defines an optimization used to increase or decrease the rendering resolution
  95135. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95136. */
  95137. var HardwareScalingOptimization = /** @class */ (function (_super) {
  95138. __extends(HardwareScalingOptimization, _super);
  95139. /**
  95140. * Creates the HardwareScalingOptimization object
  95141. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95142. * @param maximumScale defines the maximum scale to use (2 by default)
  95143. * @param step defines the step to use between two passes (0.5 by default)
  95144. */
  95145. function HardwareScalingOptimization(
  95146. /**
  95147. * Defines the priority of this optimization (0 by default which means first in the list)
  95148. */
  95149. priority,
  95150. /**
  95151. * Defines the maximum scale to use (2 by default)
  95152. */
  95153. maximumScale,
  95154. /**
  95155. * Defines the step to use between two passes (0.5 by default)
  95156. */
  95157. step) {
  95158. if (priority === void 0) { priority = 0; }
  95159. if (maximumScale === void 0) { maximumScale = 2; }
  95160. if (step === void 0) { step = 0.25; }
  95161. var _this = _super.call(this, priority) || this;
  95162. _this.priority = priority;
  95163. _this.maximumScale = maximumScale;
  95164. _this.step = step;
  95165. _this._currentScale = -1;
  95166. _this._directionOffset = 1;
  95167. return _this;
  95168. }
  95169. /**
  95170. * Gets a string describing the action executed by the current optimization
  95171. * @return description string
  95172. */
  95173. HardwareScalingOptimization.prototype.getDescription = function () {
  95174. return "Setting hardware scaling level to " + this._currentScale;
  95175. };
  95176. /**
  95177. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95178. * @param scene defines the current scene where to apply this optimization
  95179. * @param optimizer defines the current optimizer
  95180. * @returns true if everything that can be done was applied
  95181. */
  95182. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  95183. if (this._currentScale === -1) {
  95184. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  95185. if (this._currentScale > this.maximumScale) {
  95186. this._directionOffset = -1;
  95187. }
  95188. }
  95189. this._currentScale += this._directionOffset * this.step;
  95190. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  95191. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  95192. };
  95193. ;
  95194. return HardwareScalingOptimization;
  95195. }(SceneOptimization));
  95196. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  95197. /**
  95198. * Defines an optimization used to remove shadows
  95199. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95200. */
  95201. var ShadowsOptimization = /** @class */ (function (_super) {
  95202. __extends(ShadowsOptimization, _super);
  95203. function ShadowsOptimization() {
  95204. return _super !== null && _super.apply(this, arguments) || this;
  95205. }
  95206. /**
  95207. * Gets a string describing the action executed by the current optimization
  95208. * @return description string
  95209. */
  95210. ShadowsOptimization.prototype.getDescription = function () {
  95211. return "Turning shadows on/off";
  95212. };
  95213. /**
  95214. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95215. * @param scene defines the current scene where to apply this optimization
  95216. * @param optimizer defines the current optimizer
  95217. * @returns true if everything that can be done was applied
  95218. */
  95219. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  95220. scene.shadowsEnabled = optimizer.isInImprovementMode;
  95221. return true;
  95222. };
  95223. ;
  95224. return ShadowsOptimization;
  95225. }(SceneOptimization));
  95226. BABYLON.ShadowsOptimization = ShadowsOptimization;
  95227. /**
  95228. * Defines an optimization used to turn post-processes off
  95229. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95230. */
  95231. var PostProcessesOptimization = /** @class */ (function (_super) {
  95232. __extends(PostProcessesOptimization, _super);
  95233. function PostProcessesOptimization() {
  95234. return _super !== null && _super.apply(this, arguments) || this;
  95235. }
  95236. /**
  95237. * Gets a string describing the action executed by the current optimization
  95238. * @return description string
  95239. */
  95240. PostProcessesOptimization.prototype.getDescription = function () {
  95241. return "Turning post-processes on/off";
  95242. };
  95243. /**
  95244. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95245. * @param scene defines the current scene where to apply this optimization
  95246. * @param optimizer defines the current optimizer
  95247. * @returns true if everything that can be done was applied
  95248. */
  95249. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  95250. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  95251. return true;
  95252. };
  95253. ;
  95254. return PostProcessesOptimization;
  95255. }(SceneOptimization));
  95256. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  95257. /**
  95258. * Defines an optimization used to turn lens flares off
  95259. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95260. */
  95261. var LensFlaresOptimization = /** @class */ (function (_super) {
  95262. __extends(LensFlaresOptimization, _super);
  95263. function LensFlaresOptimization() {
  95264. return _super !== null && _super.apply(this, arguments) || this;
  95265. }
  95266. /**
  95267. * Gets a string describing the action executed by the current optimization
  95268. * @return description string
  95269. */
  95270. LensFlaresOptimization.prototype.getDescription = function () {
  95271. return "Turning lens flares on/off";
  95272. };
  95273. /**
  95274. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95275. * @param scene defines the current scene where to apply this optimization
  95276. * @param optimizer defines the current optimizer
  95277. * @returns true if everything that can be done was applied
  95278. */
  95279. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  95280. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  95281. return true;
  95282. };
  95283. ;
  95284. return LensFlaresOptimization;
  95285. }(SceneOptimization));
  95286. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  95287. /**
  95288. * Defines an optimization based on user defined callback.
  95289. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95290. */
  95291. var CustomOptimization = /** @class */ (function (_super) {
  95292. __extends(CustomOptimization, _super);
  95293. function CustomOptimization() {
  95294. return _super !== null && _super.apply(this, arguments) || this;
  95295. }
  95296. /**
  95297. * Gets a string describing the action executed by the current optimization
  95298. * @returns description string
  95299. */
  95300. CustomOptimization.prototype.getDescription = function () {
  95301. if (this.onGetDescription) {
  95302. return this.onGetDescription();
  95303. }
  95304. return "Running user defined callback";
  95305. };
  95306. /**
  95307. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95308. * @param scene defines the current scene where to apply this optimization
  95309. * @param optimizer defines the current optimizer
  95310. * @returns true if everything that can be done was applied
  95311. */
  95312. CustomOptimization.prototype.apply = function (scene, optimizer) {
  95313. if (this.onApply) {
  95314. return this.onApply(scene, optimizer);
  95315. }
  95316. return true;
  95317. };
  95318. ;
  95319. return CustomOptimization;
  95320. }(SceneOptimization));
  95321. BABYLON.CustomOptimization = CustomOptimization;
  95322. /**
  95323. * Defines an optimization used to turn particles off
  95324. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95325. */
  95326. var ParticlesOptimization = /** @class */ (function (_super) {
  95327. __extends(ParticlesOptimization, _super);
  95328. function ParticlesOptimization() {
  95329. return _super !== null && _super.apply(this, arguments) || this;
  95330. }
  95331. /**
  95332. * Gets a string describing the action executed by the current optimization
  95333. * @return description string
  95334. */
  95335. ParticlesOptimization.prototype.getDescription = function () {
  95336. return "Turning particles on/off";
  95337. };
  95338. /**
  95339. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95340. * @param scene defines the current scene where to apply this optimization
  95341. * @param optimizer defines the current optimizer
  95342. * @returns true if everything that can be done was applied
  95343. */
  95344. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  95345. scene.particlesEnabled = optimizer.isInImprovementMode;
  95346. return true;
  95347. };
  95348. ;
  95349. return ParticlesOptimization;
  95350. }(SceneOptimization));
  95351. BABYLON.ParticlesOptimization = ParticlesOptimization;
  95352. /**
  95353. * Defines an optimization used to turn render targets off
  95354. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95355. */
  95356. var RenderTargetsOptimization = /** @class */ (function (_super) {
  95357. __extends(RenderTargetsOptimization, _super);
  95358. function RenderTargetsOptimization() {
  95359. return _super !== null && _super.apply(this, arguments) || this;
  95360. }
  95361. /**
  95362. * Gets a string describing the action executed by the current optimization
  95363. * @return description string
  95364. */
  95365. RenderTargetsOptimization.prototype.getDescription = function () {
  95366. return "Turning render targets off";
  95367. };
  95368. /**
  95369. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95370. * @param scene defines the current scene where to apply this optimization
  95371. * @param optimizer defines the current optimizer
  95372. * @returns true if everything that can be done was applied
  95373. */
  95374. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  95375. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  95376. return true;
  95377. };
  95378. ;
  95379. return RenderTargetsOptimization;
  95380. }(SceneOptimization));
  95381. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  95382. /**
  95383. * Defines an optimization used to merge meshes with compatible materials
  95384. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95385. */
  95386. var MergeMeshesOptimization = /** @class */ (function (_super) {
  95387. __extends(MergeMeshesOptimization, _super);
  95388. function MergeMeshesOptimization() {
  95389. var _this = _super !== null && _super.apply(this, arguments) || this;
  95390. _this._canBeMerged = function (abstractMesh) {
  95391. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  95392. return false;
  95393. }
  95394. var mesh = abstractMesh;
  95395. if (!mesh.isVisible || !mesh.isEnabled()) {
  95396. return false;
  95397. }
  95398. if (mesh.instances.length > 0) {
  95399. return false;
  95400. }
  95401. if (mesh.skeleton || mesh.hasLODLevels) {
  95402. return false;
  95403. }
  95404. if (mesh.parent) {
  95405. return false;
  95406. }
  95407. return true;
  95408. };
  95409. return _this;
  95410. }
  95411. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95412. /**
  95413. * Gets or sets a boolean which defines if optimization octree has to be updated
  95414. */
  95415. get: function () {
  95416. return MergeMeshesOptimization._UpdateSelectionTree;
  95417. },
  95418. /**
  95419. * Gets or sets a boolean which defines if optimization octree has to be updated
  95420. */
  95421. set: function (value) {
  95422. MergeMeshesOptimization._UpdateSelectionTree = value;
  95423. },
  95424. enumerable: true,
  95425. configurable: true
  95426. });
  95427. /**
  95428. * Gets a string describing the action executed by the current optimization
  95429. * @return description string
  95430. */
  95431. MergeMeshesOptimization.prototype.getDescription = function () {
  95432. return "Merging similar meshes together";
  95433. };
  95434. /**
  95435. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95436. * @param scene defines the current scene where to apply this optimization
  95437. * @param optimizer defines the current optimizer
  95438. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95439. * @returns true if everything that can be done was applied
  95440. */
  95441. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95442. var globalPool = scene.meshes.slice(0);
  95443. var globalLength = globalPool.length;
  95444. for (var index = 0; index < globalLength; index++) {
  95445. var currentPool = new Array();
  95446. var current = globalPool[index];
  95447. // Checks
  95448. if (!this._canBeMerged(current)) {
  95449. continue;
  95450. }
  95451. currentPool.push(current);
  95452. // Find compatible meshes
  95453. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95454. var otherMesh = globalPool[subIndex];
  95455. if (!this._canBeMerged(otherMesh)) {
  95456. continue;
  95457. }
  95458. if (otherMesh.material !== current.material) {
  95459. continue;
  95460. }
  95461. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95462. continue;
  95463. }
  95464. currentPool.push(otherMesh);
  95465. globalLength--;
  95466. globalPool.splice(subIndex, 1);
  95467. subIndex--;
  95468. }
  95469. if (currentPool.length < 2) {
  95470. continue;
  95471. }
  95472. // Merge meshes
  95473. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95474. }
  95475. if (updateSelectionTree != undefined) {
  95476. if (updateSelectionTree) {
  95477. scene.createOrUpdateSelectionOctree();
  95478. }
  95479. }
  95480. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95481. scene.createOrUpdateSelectionOctree();
  95482. }
  95483. return true;
  95484. };
  95485. ;
  95486. MergeMeshesOptimization._UpdateSelectionTree = false;
  95487. return MergeMeshesOptimization;
  95488. }(SceneOptimization));
  95489. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95490. /**
  95491. * Defines a list of options used by SceneOptimizer
  95492. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95493. */
  95494. var SceneOptimizerOptions = /** @class */ (function () {
  95495. /**
  95496. * Creates a new list of options used by SceneOptimizer
  95497. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95498. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95499. */
  95500. function SceneOptimizerOptions(
  95501. /**
  95502. * Defines the target frame rate to reach (60 by default)
  95503. */
  95504. targetFrameRate,
  95505. /**
  95506. * Defines the interval between two checkes (2000ms by default)
  95507. */
  95508. trackerDuration) {
  95509. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95510. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95511. this.targetFrameRate = targetFrameRate;
  95512. this.trackerDuration = trackerDuration;
  95513. /**
  95514. * Gets the list of optimizations to apply
  95515. */
  95516. this.optimizations = new Array();
  95517. }
  95518. /**
  95519. * Add a new optimization
  95520. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95521. * @returns the current SceneOptimizerOptions
  95522. */
  95523. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95524. this.optimizations.push(optimization);
  95525. return this;
  95526. };
  95527. /**
  95528. * Add a new custom optimization
  95529. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95530. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95531. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95532. * @returns the current SceneOptimizerOptions
  95533. */
  95534. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95535. if (priority === void 0) { priority = 0; }
  95536. var optimization = new CustomOptimization(priority);
  95537. optimization.onApply = onApply;
  95538. optimization.onGetDescription = onGetDescription;
  95539. this.optimizations.push(optimization);
  95540. return this;
  95541. };
  95542. /**
  95543. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95544. * @param targetFrameRate defines the target frame rate (60 by default)
  95545. * @returns a SceneOptimizerOptions object
  95546. */
  95547. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95548. var result = new SceneOptimizerOptions(targetFrameRate);
  95549. var priority = 0;
  95550. result.addOptimization(new MergeMeshesOptimization(priority));
  95551. result.addOptimization(new ShadowsOptimization(priority));
  95552. result.addOptimization(new LensFlaresOptimization(priority));
  95553. // Next priority
  95554. priority++;
  95555. result.addOptimization(new PostProcessesOptimization(priority));
  95556. result.addOptimization(new ParticlesOptimization(priority));
  95557. // Next priority
  95558. priority++;
  95559. result.addOptimization(new TextureOptimization(priority, 1024));
  95560. return result;
  95561. };
  95562. /**
  95563. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95564. * @param targetFrameRate defines the target frame rate (60 by default)
  95565. * @returns a SceneOptimizerOptions object
  95566. */
  95567. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95568. var result = new SceneOptimizerOptions(targetFrameRate);
  95569. var priority = 0;
  95570. result.addOptimization(new MergeMeshesOptimization(priority));
  95571. result.addOptimization(new ShadowsOptimization(priority));
  95572. result.addOptimization(new LensFlaresOptimization(priority));
  95573. // Next priority
  95574. priority++;
  95575. result.addOptimization(new PostProcessesOptimization(priority));
  95576. result.addOptimization(new ParticlesOptimization(priority));
  95577. // Next priority
  95578. priority++;
  95579. result.addOptimization(new TextureOptimization(priority, 512));
  95580. // Next priority
  95581. priority++;
  95582. result.addOptimization(new RenderTargetsOptimization(priority));
  95583. // Next priority
  95584. priority++;
  95585. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95586. return result;
  95587. };
  95588. /**
  95589. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95590. * @param targetFrameRate defines the target frame rate (60 by default)
  95591. * @returns a SceneOptimizerOptions object
  95592. */
  95593. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95594. var result = new SceneOptimizerOptions(targetFrameRate);
  95595. var priority = 0;
  95596. result.addOptimization(new MergeMeshesOptimization(priority));
  95597. result.addOptimization(new ShadowsOptimization(priority));
  95598. result.addOptimization(new LensFlaresOptimization(priority));
  95599. // Next priority
  95600. priority++;
  95601. result.addOptimization(new PostProcessesOptimization(priority));
  95602. result.addOptimization(new ParticlesOptimization(priority));
  95603. // Next priority
  95604. priority++;
  95605. result.addOptimization(new TextureOptimization(priority, 256));
  95606. // Next priority
  95607. priority++;
  95608. result.addOptimization(new RenderTargetsOptimization(priority));
  95609. // Next priority
  95610. priority++;
  95611. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95612. return result;
  95613. };
  95614. return SceneOptimizerOptions;
  95615. }());
  95616. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95617. /**
  95618. * Class used to run optimizations in order to reach a target frame rate
  95619. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95620. */
  95621. var SceneOptimizer = /** @class */ (function () {
  95622. /**
  95623. * Creates a new SceneOptimizer
  95624. * @param scene defines the scene to work on
  95625. * @param options defines the options to use with the SceneOptimizer
  95626. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95627. * @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)
  95628. */
  95629. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95630. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95631. if (improvementMode === void 0) { improvementMode = false; }
  95632. var _this = this;
  95633. this._isRunning = false;
  95634. this._currentPriorityLevel = 0;
  95635. this._targetFrameRate = 60;
  95636. this._trackerDuration = 2000;
  95637. this._currentFrameRate = 0;
  95638. this._improvementMode = false;
  95639. /**
  95640. * Defines an observable called when the optimizer reaches the target frame rate
  95641. */
  95642. this.onSuccessObservable = new BABYLON.Observable();
  95643. /**
  95644. * Defines an observable called when the optimizer enables an optimization
  95645. */
  95646. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95647. /**
  95648. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95649. */
  95650. this.onFailureObservable = new BABYLON.Observable();
  95651. if (!options) {
  95652. this._options = new SceneOptimizerOptions();
  95653. }
  95654. else {
  95655. this._options = options;
  95656. }
  95657. if (this._options.targetFrameRate) {
  95658. this._targetFrameRate = this._options.targetFrameRate;
  95659. }
  95660. if (this._options.trackerDuration) {
  95661. this._trackerDuration = this._options.trackerDuration;
  95662. }
  95663. if (autoGeneratePriorities) {
  95664. var priority = 0;
  95665. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95666. var optim = _a[_i];
  95667. optim.priority = priority++;
  95668. }
  95669. }
  95670. this._improvementMode = improvementMode;
  95671. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95672. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95673. _this._sceneDisposeObserver = null;
  95674. _this.dispose();
  95675. });
  95676. }
  95677. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95678. /**
  95679. * Gets a boolean indicating if the optimizer is in improvement mode
  95680. */
  95681. get: function () {
  95682. return this._improvementMode;
  95683. },
  95684. enumerable: true,
  95685. configurable: true
  95686. });
  95687. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95688. /**
  95689. * Gets the current priority level (0 at start)
  95690. */
  95691. get: function () {
  95692. return this._currentPriorityLevel;
  95693. },
  95694. enumerable: true,
  95695. configurable: true
  95696. });
  95697. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95698. /**
  95699. * Gets the current frame rate checked by the SceneOptimizer
  95700. */
  95701. get: function () {
  95702. return this._currentFrameRate;
  95703. },
  95704. enumerable: true,
  95705. configurable: true
  95706. });
  95707. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95708. /**
  95709. * Gets or sets the current target frame rate (60 by default)
  95710. */
  95711. get: function () {
  95712. return this._targetFrameRate;
  95713. },
  95714. /**
  95715. * Gets or sets the current target frame rate (60 by default)
  95716. */
  95717. set: function (value) {
  95718. this._targetFrameRate = value;
  95719. },
  95720. enumerable: true,
  95721. configurable: true
  95722. });
  95723. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95724. /**
  95725. * Gets or sets the current interval between two checks (every 2000ms by default)
  95726. */
  95727. get: function () {
  95728. return this._trackerDuration;
  95729. },
  95730. /**
  95731. * Gets or sets the current interval between two checks (every 2000ms by default)
  95732. */
  95733. set: function (value) {
  95734. this._trackerDuration = value;
  95735. },
  95736. enumerable: true,
  95737. configurable: true
  95738. });
  95739. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95740. /**
  95741. * Gets the list of active optimizations
  95742. */
  95743. get: function () {
  95744. return this._options.optimizations;
  95745. },
  95746. enumerable: true,
  95747. configurable: true
  95748. });
  95749. /**
  95750. * Stops the current optimizer
  95751. */
  95752. SceneOptimizer.prototype.stop = function () {
  95753. this._isRunning = false;
  95754. };
  95755. /**
  95756. * Reset the optimizer to initial step (current priority level = 0)
  95757. */
  95758. SceneOptimizer.prototype.reset = function () {
  95759. this._currentPriorityLevel = 0;
  95760. };
  95761. /**
  95762. * Start the optimizer. By default it will try to reach a specific framerate
  95763. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95764. */
  95765. SceneOptimizer.prototype.start = function () {
  95766. var _this = this;
  95767. if (this._isRunning) {
  95768. return;
  95769. }
  95770. this._isRunning = true;
  95771. // Let's wait for the scene to be ready before running our check
  95772. this._scene.executeWhenReady(function () {
  95773. setTimeout(function () {
  95774. _this._checkCurrentState();
  95775. }, _this._trackerDuration);
  95776. });
  95777. };
  95778. SceneOptimizer.prototype._checkCurrentState = function () {
  95779. var _this = this;
  95780. if (!this._isRunning) {
  95781. return;
  95782. }
  95783. var scene = this._scene;
  95784. var options = this._options;
  95785. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95786. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95787. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95788. this._isRunning = false;
  95789. this.onSuccessObservable.notifyObservers(this);
  95790. return;
  95791. }
  95792. // Apply current level of optimizations
  95793. var allDone = true;
  95794. var noOptimizationApplied = true;
  95795. for (var index = 0; index < options.optimizations.length; index++) {
  95796. var optimization = options.optimizations[index];
  95797. if (optimization.priority === this._currentPriorityLevel) {
  95798. noOptimizationApplied = false;
  95799. allDone = allDone && optimization.apply(scene, this);
  95800. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95801. }
  95802. }
  95803. // If no optimization was applied, this is a failure :(
  95804. if (noOptimizationApplied) {
  95805. this._isRunning = false;
  95806. this.onFailureObservable.notifyObservers(this);
  95807. return;
  95808. }
  95809. // If all optimizations were done, move to next level
  95810. if (allDone) {
  95811. this._currentPriorityLevel++;
  95812. }
  95813. // Let's the system running for a specific amount of time before checking FPS
  95814. scene.executeWhenReady(function () {
  95815. setTimeout(function () {
  95816. _this._checkCurrentState();
  95817. }, _this._trackerDuration);
  95818. });
  95819. };
  95820. /**
  95821. * Release all resources
  95822. */
  95823. SceneOptimizer.prototype.dispose = function () {
  95824. this.stop();
  95825. this.onSuccessObservable.clear();
  95826. this.onFailureObservable.clear();
  95827. this.onNewOptimizationAppliedObservable.clear();
  95828. if (this._sceneDisposeObserver) {
  95829. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95830. }
  95831. };
  95832. /**
  95833. * Helper function to create a SceneOptimizer with one single line of code
  95834. * @param scene defines the scene to work on
  95835. * @param options defines the options to use with the SceneOptimizer
  95836. * @param onSuccess defines a callback to call on success
  95837. * @param onFailure defines a callback to call on failure
  95838. * @returns the new SceneOptimizer object
  95839. */
  95840. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95841. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95842. if (onSuccess) {
  95843. optimizer.onSuccessObservable.add(function () {
  95844. onSuccess();
  95845. });
  95846. }
  95847. if (onFailure) {
  95848. optimizer.onFailureObservable.add(function () {
  95849. onFailure();
  95850. });
  95851. }
  95852. optimizer.start();
  95853. return optimizer;
  95854. };
  95855. return SceneOptimizer;
  95856. }());
  95857. BABYLON.SceneOptimizer = SceneOptimizer;
  95858. })(BABYLON || (BABYLON = {}));
  95859. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95860. var BABYLON;
  95861. (function (BABYLON) {
  95862. var OutlineRenderer = /** @class */ (function () {
  95863. function OutlineRenderer(scene) {
  95864. this.zOffset = 1;
  95865. this._scene = scene;
  95866. }
  95867. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95868. var _this = this;
  95869. if (useOverlay === void 0) { useOverlay = false; }
  95870. var scene = this._scene;
  95871. var engine = this._scene.getEngine();
  95872. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95873. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95874. return;
  95875. }
  95876. var mesh = subMesh.getRenderingMesh();
  95877. var material = subMesh.getMaterial();
  95878. if (!material || !scene.activeCamera) {
  95879. return;
  95880. }
  95881. engine.enableEffect(this._effect);
  95882. // Logarithmic depth
  95883. if (material.useLogarithmicDepth) {
  95884. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95885. }
  95886. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95887. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95888. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95889. // Bones
  95890. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95891. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95892. }
  95893. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95894. // Alpha test
  95895. if (material && material.needAlphaTesting()) {
  95896. var alphaTexture = material.getAlphaTestTexture();
  95897. if (alphaTexture) {
  95898. this._effect.setTexture("diffuseSampler", alphaTexture);
  95899. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95900. }
  95901. }
  95902. engine.setZOffset(-this.zOffset);
  95903. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95904. engine.setZOffset(0);
  95905. };
  95906. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95907. var defines = [];
  95908. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95909. var mesh = subMesh.getMesh();
  95910. var material = subMesh.getMaterial();
  95911. if (material) {
  95912. // Alpha test
  95913. if (material.needAlphaTesting()) {
  95914. defines.push("#define ALPHATEST");
  95915. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95916. attribs.push(BABYLON.VertexBuffer.UVKind);
  95917. defines.push("#define UV1");
  95918. }
  95919. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95920. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95921. defines.push("#define UV2");
  95922. }
  95923. }
  95924. //Logarithmic depth
  95925. if (material.useLogarithmicDepth) {
  95926. defines.push("#define LOGARITHMICDEPTH");
  95927. }
  95928. }
  95929. // Bones
  95930. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95933. if (mesh.numBoneInfluencers > 4) {
  95934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95936. }
  95937. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95938. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95939. }
  95940. else {
  95941. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95942. }
  95943. // Instances
  95944. if (useInstances) {
  95945. defines.push("#define INSTANCES");
  95946. attribs.push("world0");
  95947. attribs.push("world1");
  95948. attribs.push("world2");
  95949. attribs.push("world3");
  95950. }
  95951. // Get correct effect
  95952. var join = defines.join("\n");
  95953. if (this._cachedDefines !== join) {
  95954. this._cachedDefines = join;
  95955. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95956. }
  95957. return this._effect.isReady();
  95958. };
  95959. return OutlineRenderer;
  95960. }());
  95961. BABYLON.OutlineRenderer = OutlineRenderer;
  95962. })(BABYLON || (BABYLON = {}));
  95963. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95964. var BABYLON;
  95965. (function (BABYLON) {
  95966. var FaceAdjacencies = /** @class */ (function () {
  95967. function FaceAdjacencies() {
  95968. this.edges = new Array();
  95969. this.edgesConnectedCount = 0;
  95970. }
  95971. return FaceAdjacencies;
  95972. }());
  95973. var EdgesRenderer = /** @class */ (function () {
  95974. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95975. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95976. if (epsilon === void 0) { epsilon = 0.95; }
  95977. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95978. this.edgesWidthScalerForOrthographic = 1000.0;
  95979. this.edgesWidthScalerForPerspective = 50.0;
  95980. this._linesPositions = new Array();
  95981. this._linesNormals = new Array();
  95982. this._linesIndices = new Array();
  95983. this._buffers = {};
  95984. this._checkVerticesInsteadOfIndices = false;
  95985. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95986. this.isEnabled = true;
  95987. this._source = source;
  95988. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95989. this._epsilon = epsilon;
  95990. this._prepareRessources();
  95991. this._generateEdgesLines();
  95992. }
  95993. EdgesRenderer.prototype._prepareRessources = function () {
  95994. if (this._lineShader) {
  95995. return;
  95996. }
  95997. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95998. attributes: ["position", "normal"],
  95999. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  96000. });
  96001. this._lineShader.disableDepthWrite = true;
  96002. this._lineShader.backFaceCulling = false;
  96003. };
  96004. EdgesRenderer.prototype._rebuild = function () {
  96005. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96006. if (buffer) {
  96007. buffer._rebuild();
  96008. }
  96009. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96010. if (buffer) {
  96011. buffer._rebuild();
  96012. }
  96013. var scene = this._source.getScene();
  96014. var engine = scene.getEngine();
  96015. this._ib = engine.createIndexBuffer(this._linesIndices);
  96016. };
  96017. EdgesRenderer.prototype.dispose = function () {
  96018. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  96019. if (buffer) {
  96020. buffer.dispose();
  96021. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  96022. }
  96023. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  96024. if (buffer) {
  96025. buffer.dispose();
  96026. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  96027. }
  96028. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  96029. this._lineShader.dispose();
  96030. };
  96031. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  96032. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  96033. return 0;
  96034. }
  96035. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  96036. return 1;
  96037. }
  96038. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  96039. return 2;
  96040. }
  96041. return -1;
  96042. };
  96043. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  96044. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  96045. return 0;
  96046. }
  96047. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  96048. return 1;
  96049. }
  96050. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  96051. return 2;
  96052. }
  96053. return -1;
  96054. };
  96055. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  96056. var needToCreateLine;
  96057. if (edge === undefined) {
  96058. needToCreateLine = true;
  96059. }
  96060. else {
  96061. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  96062. needToCreateLine = dotProduct < this._epsilon;
  96063. }
  96064. if (needToCreateLine) {
  96065. var offset = this._linesPositions.length / 3;
  96066. var normal = p0.subtract(p1);
  96067. normal.normalize();
  96068. // Positions
  96069. this._linesPositions.push(p0.x);
  96070. this._linesPositions.push(p0.y);
  96071. this._linesPositions.push(p0.z);
  96072. this._linesPositions.push(p0.x);
  96073. this._linesPositions.push(p0.y);
  96074. this._linesPositions.push(p0.z);
  96075. this._linesPositions.push(p1.x);
  96076. this._linesPositions.push(p1.y);
  96077. this._linesPositions.push(p1.z);
  96078. this._linesPositions.push(p1.x);
  96079. this._linesPositions.push(p1.y);
  96080. this._linesPositions.push(p1.z);
  96081. // Normals
  96082. this._linesNormals.push(p1.x);
  96083. this._linesNormals.push(p1.y);
  96084. this._linesNormals.push(p1.z);
  96085. this._linesNormals.push(-1);
  96086. this._linesNormals.push(p1.x);
  96087. this._linesNormals.push(p1.y);
  96088. this._linesNormals.push(p1.z);
  96089. this._linesNormals.push(1);
  96090. this._linesNormals.push(p0.x);
  96091. this._linesNormals.push(p0.y);
  96092. this._linesNormals.push(p0.z);
  96093. this._linesNormals.push(-1);
  96094. this._linesNormals.push(p0.x);
  96095. this._linesNormals.push(p0.y);
  96096. this._linesNormals.push(p0.z);
  96097. this._linesNormals.push(1);
  96098. // Indices
  96099. this._linesIndices.push(offset);
  96100. this._linesIndices.push(offset + 1);
  96101. this._linesIndices.push(offset + 2);
  96102. this._linesIndices.push(offset);
  96103. this._linesIndices.push(offset + 2);
  96104. this._linesIndices.push(offset + 3);
  96105. }
  96106. };
  96107. EdgesRenderer.prototype._generateEdgesLines = function () {
  96108. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  96109. var indices = this._source.getIndices();
  96110. if (!indices || !positions) {
  96111. return;
  96112. }
  96113. // First let's find adjacencies
  96114. var adjacencies = new Array();
  96115. var faceNormals = new Array();
  96116. var index;
  96117. var faceAdjacencies;
  96118. // Prepare faces
  96119. for (index = 0; index < indices.length; index += 3) {
  96120. faceAdjacencies = new FaceAdjacencies();
  96121. var p0Index = indices[index];
  96122. var p1Index = indices[index + 1];
  96123. var p2Index = indices[index + 2];
  96124. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  96125. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  96126. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  96127. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  96128. faceNormal.normalize();
  96129. faceNormals.push(faceNormal);
  96130. adjacencies.push(faceAdjacencies);
  96131. }
  96132. // Scan
  96133. for (index = 0; index < adjacencies.length; index++) {
  96134. faceAdjacencies = adjacencies[index];
  96135. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  96136. var otherFaceAdjacencies = adjacencies[otherIndex];
  96137. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  96138. break;
  96139. }
  96140. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  96141. continue;
  96142. }
  96143. var otherP0 = indices[otherIndex * 3];
  96144. var otherP1 = indices[otherIndex * 3 + 1];
  96145. var otherP2 = indices[otherIndex * 3 + 2];
  96146. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  96147. var otherEdgeIndex = 0;
  96148. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  96149. continue;
  96150. }
  96151. switch (edgeIndex) {
  96152. case 0:
  96153. if (this._checkVerticesInsteadOfIndices) {
  96154. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96155. }
  96156. else {
  96157. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  96158. }
  96159. break;
  96160. case 1:
  96161. if (this._checkVerticesInsteadOfIndices) {
  96162. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96163. }
  96164. else {
  96165. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  96166. }
  96167. break;
  96168. case 2:
  96169. if (this._checkVerticesInsteadOfIndices) {
  96170. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  96171. }
  96172. else {
  96173. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  96174. }
  96175. break;
  96176. }
  96177. if (otherEdgeIndex === -1) {
  96178. continue;
  96179. }
  96180. faceAdjacencies.edges[edgeIndex] = otherIndex;
  96181. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  96182. faceAdjacencies.edgesConnectedCount++;
  96183. otherFaceAdjacencies.edgesConnectedCount++;
  96184. if (faceAdjacencies.edgesConnectedCount === 3) {
  96185. break;
  96186. }
  96187. }
  96188. }
  96189. }
  96190. // Create lines
  96191. for (index = 0; index < adjacencies.length; index++) {
  96192. // 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
  96193. var current = adjacencies[index];
  96194. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  96195. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  96196. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  96197. }
  96198. // Merge into a single mesh
  96199. var engine = this._source.getScene().getEngine();
  96200. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  96201. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  96202. this._ib = engine.createIndexBuffer(this._linesIndices);
  96203. this._indicesCount = this._linesIndices.length;
  96204. };
  96205. EdgesRenderer.prototype.render = function () {
  96206. var scene = this._source.getScene();
  96207. if (!this._lineShader.isReady() || !scene.activeCamera) {
  96208. return;
  96209. }
  96210. var engine = scene.getEngine();
  96211. this._lineShader._preBind();
  96212. // VBOs
  96213. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  96214. scene.resetCachedMaterial();
  96215. this._lineShader.setColor4("color", this._source.edgesColor);
  96216. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  96217. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  96218. }
  96219. else {
  96220. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  96221. }
  96222. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  96223. this._lineShader.bind(this._source.getWorldMatrix());
  96224. // Draw order
  96225. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  96226. this._lineShader.unbind();
  96227. engine.setDepthWrite(true);
  96228. };
  96229. return EdgesRenderer;
  96230. }());
  96231. BABYLON.EdgesRenderer = EdgesRenderer;
  96232. })(BABYLON || (BABYLON = {}));
  96233. //# sourceMappingURL=babylon.edgesRenderer.js.map
  96234. var BABYLON;
  96235. (function (BABYLON) {
  96236. // Adds the parser to the scene parsers.
  96237. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  96238. if (parsedData.effectLayers) {
  96239. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  96240. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  96241. container.effectLayers.push(effectLayer);
  96242. }
  96243. }
  96244. });
  96245. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  96246. var index = this.effectLayers.indexOf(toRemove);
  96247. if (index !== -1) {
  96248. this.effectLayers.splice(index, 1);
  96249. }
  96250. return index;
  96251. };
  96252. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  96253. this.effectLayers.push(newEffectLayer);
  96254. };
  96255. /**
  96256. * Defines the layer scene component responsible to manage any effect layers
  96257. * in a given scene.
  96258. */
  96259. var EffectLayerSceneComponent = /** @class */ (function () {
  96260. /**
  96261. * Creates a new instance of the component for the given scene
  96262. * @param scene Defines the scene to register the component in
  96263. */
  96264. function EffectLayerSceneComponent(scene) {
  96265. /**
  96266. * The component name helpfull to identify the component in the list of scene components.
  96267. */
  96268. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  96269. this._renderEffects = false;
  96270. this._needStencil = false;
  96271. this._previousStencilState = false;
  96272. this.scene = scene;
  96273. this._engine = scene.getEngine();
  96274. scene.effectLayers = new Array();
  96275. }
  96276. /**
  96277. * Registers the component in a given scene
  96278. */
  96279. EffectLayerSceneComponent.prototype.register = function () {
  96280. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  96281. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  96282. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  96283. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  96284. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  96285. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  96286. };
  96287. /**
  96288. * Rebuilds the elements related to this component in case of
  96289. * context lost for instance.
  96290. */
  96291. EffectLayerSceneComponent.prototype.rebuild = function () {
  96292. var layers = this.scene.effectLayers;
  96293. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  96294. var effectLayer = layers_1[_i];
  96295. effectLayer._rebuild();
  96296. }
  96297. };
  96298. /**
  96299. * Serializes the component data to the specified json object
  96300. * @param serializationObject The object to serialize to
  96301. */
  96302. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  96303. // Effect layers
  96304. serializationObject.effectLayers = [];
  96305. var layers = this.scene.effectLayers;
  96306. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  96307. var effectLayer = layers_2[_i];
  96308. if (effectLayer.serialize) {
  96309. serializationObject.effectLayers.push(effectLayer.serialize());
  96310. }
  96311. }
  96312. };
  96313. /**
  96314. * Adds all the element from the container to the scene
  96315. * @param container the container holding the elements
  96316. */
  96317. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  96318. var _this = this;
  96319. if (!container.effectLayers) {
  96320. return;
  96321. }
  96322. container.effectLayers.forEach(function (o) {
  96323. _this.scene.addEffectLayer(o);
  96324. });
  96325. };
  96326. /**
  96327. * Removes all the elements in the container from the scene
  96328. * @param container contains the elements to remove
  96329. */
  96330. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  96331. var _this = this;
  96332. if (!container.effectLayers) {
  96333. return;
  96334. }
  96335. container.effectLayers.forEach(function (o) {
  96336. _this.scene.removeEffectLayer(o);
  96337. });
  96338. };
  96339. /**
  96340. * Disposes the component and the associated ressources.
  96341. */
  96342. EffectLayerSceneComponent.prototype.dispose = function () {
  96343. var layers = this.scene.effectLayers;
  96344. while (layers.length) {
  96345. layers[0].dispose();
  96346. }
  96347. };
  96348. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  96349. var layers = this.scene.effectLayers;
  96350. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  96351. var layer = layers_3[_i];
  96352. if (!layer.hasMesh(mesh)) {
  96353. continue;
  96354. }
  96355. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  96356. var subMesh = _b[_a];
  96357. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  96358. return false;
  96359. }
  96360. }
  96361. }
  96362. return true;
  96363. };
  96364. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  96365. this._renderEffects = false;
  96366. this._needStencil = false;
  96367. var layers = this.scene.effectLayers;
  96368. if (layers && layers.length > 0) {
  96369. this._previousStencilState = this._engine.getStencilBuffer();
  96370. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  96371. var effectLayer = layers_4[_i];
  96372. if (effectLayer.shouldRender() &&
  96373. (!effectLayer.camera ||
  96374. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  96375. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  96376. this._renderEffects = true;
  96377. this._needStencil = this._needStencil || effectLayer.needStencil();
  96378. var renderTarget = effectLayer._mainTexture;
  96379. if (renderTarget._shouldRender()) {
  96380. this.scene.incrementRenderId();
  96381. renderTarget.render(false, false);
  96382. }
  96383. }
  96384. }
  96385. this.scene.incrementRenderId();
  96386. }
  96387. };
  96388. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  96389. // Activate effect Layer stencil
  96390. if (this._needStencil) {
  96391. this._engine.setStencilBuffer(true);
  96392. }
  96393. };
  96394. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  96395. // Restore effect Layer stencil
  96396. if (this._needStencil) {
  96397. this._engine.setStencilBuffer(this._previousStencilState);
  96398. }
  96399. };
  96400. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  96401. if (this._renderEffects) {
  96402. this._engine.setDepthBuffer(false);
  96403. var layers = this.scene.effectLayers;
  96404. for (var i = 0; i < layers.length; i++) {
  96405. var effectLayer = layers[i];
  96406. if (effectLayer.renderingGroupId === renderingGroupId) {
  96407. if (effectLayer.shouldRender()) {
  96408. effectLayer.render();
  96409. }
  96410. }
  96411. }
  96412. this._engine.setDepthBuffer(true);
  96413. }
  96414. };
  96415. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  96416. if (this._renderEffects) {
  96417. this._draw(-1);
  96418. }
  96419. };
  96420. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  96421. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  96422. this._draw(index);
  96423. }
  96424. };
  96425. return EffectLayerSceneComponent;
  96426. }());
  96427. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96428. })(BABYLON || (BABYLON = {}));
  96429. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96430. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96431. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96432. s = arguments[i];
  96433. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96434. t[p] = s[p];
  96435. }
  96436. return t;
  96437. };
  96438. var BABYLON;
  96439. (function (BABYLON) {
  96440. /**
  96441. * The effect layer Helps adding post process effect blended with the main pass.
  96442. *
  96443. * This can be for instance use to generate glow or higlight effects on the scene.
  96444. *
  96445. * The effect layer class can not be used directly and is intented to inherited from to be
  96446. * customized per effects.
  96447. */
  96448. var EffectLayer = /** @class */ (function () {
  96449. /**
  96450. * Instantiates a new effect Layer and references it in the scene.
  96451. * @param name The name of the layer
  96452. * @param scene The scene to use the layer in
  96453. */
  96454. function EffectLayer(
  96455. /** The Friendly of the effect in the scene */
  96456. name, scene) {
  96457. this._vertexBuffers = {};
  96458. this._maxSize = 0;
  96459. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96460. this._shouldRender = true;
  96461. this._postProcesses = [];
  96462. this._textures = [];
  96463. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96464. /**
  96465. * The clear color of the texture used to generate the glow map.
  96466. */
  96467. this.neutralColor = new BABYLON.Color4();
  96468. /**
  96469. * Specifies wether the highlight layer is enabled or not.
  96470. */
  96471. this.isEnabled = true;
  96472. /**
  96473. * An event triggered when the effect layer has been disposed.
  96474. */
  96475. this.onDisposeObservable = new BABYLON.Observable();
  96476. /**
  96477. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96478. */
  96479. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96480. /**
  96481. * An event triggered when the generated texture is being merged in the scene.
  96482. */
  96483. this.onBeforeComposeObservable = new BABYLON.Observable();
  96484. /**
  96485. * An event triggered when the generated texture has been merged in the scene.
  96486. */
  96487. this.onAfterComposeObservable = new BABYLON.Observable();
  96488. /**
  96489. * An event triggered when the efffect layer changes its size.
  96490. */
  96491. this.onSizeChangedObservable = new BABYLON.Observable();
  96492. this.name = name;
  96493. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96494. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96495. if (!component) {
  96496. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96497. this._scene._addComponent(component);
  96498. }
  96499. this._engine = this._scene.getEngine();
  96500. this._maxSize = this._engine.getCaps().maxTextureSize;
  96501. this._scene.effectLayers.push(this);
  96502. // Generate Buffers
  96503. this._generateIndexBuffer();
  96504. this._genrateVertexBuffer();
  96505. }
  96506. Object.defineProperty(EffectLayer.prototype, "camera", {
  96507. /**
  96508. * Gets the camera attached to the layer.
  96509. */
  96510. get: function () {
  96511. return this._effectLayerOptions.camera;
  96512. },
  96513. enumerable: true,
  96514. configurable: true
  96515. });
  96516. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  96517. /**
  96518. * Gets the rendering group id the layer should render in.
  96519. */
  96520. get: function () {
  96521. return this._effectLayerOptions.renderingGroupId;
  96522. },
  96523. enumerable: true,
  96524. configurable: true
  96525. });
  96526. /**
  96527. * Initializes the effect layer with the required options.
  96528. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96529. */
  96530. EffectLayer.prototype._init = function (options) {
  96531. // Adapt options
  96532. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  96533. this._setMainTextureSize();
  96534. this._createMainTexture();
  96535. this._createTextureAndPostProcesses();
  96536. this._mergeEffect = this._createMergeEffect();
  96537. };
  96538. /**
  96539. * Generates the index buffer of the full screen quad blending to the main canvas.
  96540. */
  96541. EffectLayer.prototype._generateIndexBuffer = function () {
  96542. // Indices
  96543. var indices = [];
  96544. indices.push(0);
  96545. indices.push(1);
  96546. indices.push(2);
  96547. indices.push(0);
  96548. indices.push(2);
  96549. indices.push(3);
  96550. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96551. };
  96552. /**
  96553. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96554. */
  96555. EffectLayer.prototype._genrateVertexBuffer = function () {
  96556. // VBO
  96557. var vertices = [];
  96558. vertices.push(1, 1);
  96559. vertices.push(-1, 1);
  96560. vertices.push(-1, -1);
  96561. vertices.push(1, -1);
  96562. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96563. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96564. };
  96565. /**
  96566. * Sets the main texture desired size which is the closest power of two
  96567. * of the engine canvas size.
  96568. */
  96569. EffectLayer.prototype._setMainTextureSize = function () {
  96570. if (this._effectLayerOptions.mainTextureFixedSize) {
  96571. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96572. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96573. }
  96574. else {
  96575. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96576. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96577. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96578. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96579. }
  96580. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96581. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96582. };
  96583. /**
  96584. * Creates the main texture for the effect layer.
  96585. */
  96586. EffectLayer.prototype._createMainTexture = function () {
  96587. var _this = this;
  96588. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96589. width: this._mainTextureDesiredSize.width,
  96590. height: this._mainTextureDesiredSize.height
  96591. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96592. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96593. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96594. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96595. this._mainTexture.anisotropicFilteringLevel = 1;
  96596. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96597. this._mainTexture.renderParticles = false;
  96598. this._mainTexture.renderList = null;
  96599. this._mainTexture.ignoreCameraViewport = true;
  96600. // Custom render function
  96601. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96602. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96603. var index;
  96604. var engine = _this._scene.getEngine();
  96605. if (depthOnlySubMeshes.length) {
  96606. engine.setColorWrite(false);
  96607. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96608. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96609. }
  96610. engine.setColorWrite(true);
  96611. }
  96612. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96613. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96614. }
  96615. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96616. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96617. }
  96618. for (index = 0; index < transparentSubMeshes.length; index++) {
  96619. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96620. }
  96621. };
  96622. this._mainTexture.onClearObservable.add(function (engine) {
  96623. engine.clear(_this.neutralColor, true, true, true);
  96624. });
  96625. };
  96626. /**
  96627. * Checks for the readiness of the element composing the layer.
  96628. * @param subMesh the mesh to check for
  96629. * @param useInstances specify wether or not to use instances to render the mesh
  96630. * @param emissiveTexture the associated emissive texture used to generate the glow
  96631. * @return true if ready otherwise, false
  96632. */
  96633. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96634. var material = subMesh.getMaterial();
  96635. if (!material) {
  96636. return false;
  96637. }
  96638. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96639. return false;
  96640. }
  96641. var defines = [];
  96642. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96643. var mesh = subMesh.getMesh();
  96644. var uv1 = false;
  96645. var uv2 = false;
  96646. // Alpha test
  96647. if (material && material.needAlphaTesting()) {
  96648. var alphaTexture = material.getAlphaTestTexture();
  96649. if (alphaTexture) {
  96650. defines.push("#define ALPHATEST");
  96651. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96652. alphaTexture.coordinatesIndex === 1) {
  96653. defines.push("#define DIFFUSEUV2");
  96654. uv2 = true;
  96655. }
  96656. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96657. defines.push("#define DIFFUSEUV1");
  96658. uv1 = true;
  96659. }
  96660. }
  96661. }
  96662. // Emissive
  96663. if (emissiveTexture) {
  96664. defines.push("#define EMISSIVE");
  96665. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96666. emissiveTexture.coordinatesIndex === 1) {
  96667. defines.push("#define EMISSIVEUV2");
  96668. uv2 = true;
  96669. }
  96670. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96671. defines.push("#define EMISSIVEUV1");
  96672. uv1 = true;
  96673. }
  96674. }
  96675. if (uv1) {
  96676. attribs.push(BABYLON.VertexBuffer.UVKind);
  96677. defines.push("#define UV1");
  96678. }
  96679. if (uv2) {
  96680. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96681. defines.push("#define UV2");
  96682. }
  96683. // Bones
  96684. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96685. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96686. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96687. if (mesh.numBoneInfluencers > 4) {
  96688. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96689. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96690. }
  96691. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96692. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96693. }
  96694. else {
  96695. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96696. }
  96697. // Morph targets
  96698. var manager = mesh.morphTargetManager;
  96699. var morphInfluencers = 0;
  96700. if (manager) {
  96701. if (manager.numInfluencers > 0) {
  96702. defines.push("#define MORPHTARGETS");
  96703. morphInfluencers = manager.numInfluencers;
  96704. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96705. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96706. }
  96707. }
  96708. // Instances
  96709. if (useInstances) {
  96710. defines.push("#define INSTANCES");
  96711. attribs.push("world0");
  96712. attribs.push("world1");
  96713. attribs.push("world2");
  96714. attribs.push("world3");
  96715. }
  96716. // Get correct effect
  96717. var join = defines.join("\n");
  96718. if (this._cachedDefines !== join) {
  96719. this._cachedDefines = join;
  96720. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96721. }
  96722. return this._effectLayerMapGenerationEffect.isReady();
  96723. };
  96724. /**
  96725. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96726. */
  96727. EffectLayer.prototype.render = function () {
  96728. var currentEffect = this._mergeEffect;
  96729. // Check
  96730. if (!currentEffect.isReady())
  96731. return;
  96732. for (var i = 0; i < this._postProcesses.length; i++) {
  96733. if (!this._postProcesses[i].isReady()) {
  96734. return;
  96735. }
  96736. }
  96737. var engine = this._scene.getEngine();
  96738. this.onBeforeComposeObservable.notifyObservers(this);
  96739. // Render
  96740. engine.enableEffect(currentEffect);
  96741. engine.setState(false);
  96742. // VBOs
  96743. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96744. // Cache
  96745. var previousAlphaMode = engine.getAlphaMode();
  96746. // Go Blend.
  96747. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96748. // Blends the map on the main canvas.
  96749. this._internalRender(currentEffect);
  96750. // Restore Alpha
  96751. engine.setAlphaMode(previousAlphaMode);
  96752. this.onAfterComposeObservable.notifyObservers(this);
  96753. // Handle size changes.
  96754. var size = this._mainTexture.getSize();
  96755. this._setMainTextureSize();
  96756. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96757. // Recreate RTT and post processes on size change.
  96758. this.onSizeChangedObservable.notifyObservers(this);
  96759. this._disposeTextureAndPostProcesses();
  96760. this._createMainTexture();
  96761. this._createTextureAndPostProcesses();
  96762. }
  96763. };
  96764. /**
  96765. * Determine if a given mesh will be used in the current effect.
  96766. * @param mesh mesh to test
  96767. * @returns true if the mesh will be used
  96768. */
  96769. EffectLayer.prototype.hasMesh = function (mesh) {
  96770. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  96771. return true;
  96772. }
  96773. return false;
  96774. };
  96775. /**
  96776. * Returns true if the layer contains information to display, otherwise false.
  96777. * @returns true if the glow layer should be rendered
  96778. */
  96779. EffectLayer.prototype.shouldRender = function () {
  96780. return this.isEnabled && this._shouldRender;
  96781. };
  96782. /**
  96783. * Returns true if the mesh should render, otherwise false.
  96784. * @param mesh The mesh to render
  96785. * @returns true if it should render otherwise false
  96786. */
  96787. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96788. return true;
  96789. };
  96790. /**
  96791. * Returns true if the mesh should render, otherwise false.
  96792. * @param mesh The mesh to render
  96793. * @returns true if it should render otherwise false
  96794. */
  96795. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96796. return true;
  96797. };
  96798. /**
  96799. * Renders the submesh passed in parameter to the generation map.
  96800. */
  96801. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96802. var _this = this;
  96803. if (!this.shouldRender()) {
  96804. return;
  96805. }
  96806. var material = subMesh.getMaterial();
  96807. var mesh = subMesh.getRenderingMesh();
  96808. var scene = this._scene;
  96809. var engine = scene.getEngine();
  96810. if (!material) {
  96811. return;
  96812. }
  96813. // Do not block in blend mode.
  96814. if (material.needAlphaBlendingForMesh(mesh)) {
  96815. return;
  96816. }
  96817. // Culling
  96818. engine.setState(material.backFaceCulling);
  96819. // Managing instances
  96820. var batch = mesh._getInstancesRenderList(subMesh._id);
  96821. if (batch.mustReturn) {
  96822. return;
  96823. }
  96824. // Early Exit per mesh
  96825. if (!this._shouldRenderMesh(mesh)) {
  96826. return;
  96827. }
  96828. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96829. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96830. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96831. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96832. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96833. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96834. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96835. // Alpha test
  96836. if (material && material.needAlphaTesting()) {
  96837. var alphaTexture = material.getAlphaTestTexture();
  96838. if (alphaTexture) {
  96839. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96840. var textureMatrix = alphaTexture.getTextureMatrix();
  96841. if (textureMatrix) {
  96842. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96843. }
  96844. }
  96845. }
  96846. // Glow emissive only
  96847. if (this._emissiveTextureAndColor.texture) {
  96848. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96849. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96850. }
  96851. // Bones
  96852. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96853. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96854. }
  96855. // Morph targets
  96856. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96857. // Draw
  96858. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96859. }
  96860. else {
  96861. // Need to reset refresh rate of the main map
  96862. this._mainTexture.resetRefreshCounter();
  96863. }
  96864. };
  96865. /**
  96866. * Rebuild the required buffers.
  96867. * @hidden Internal use only.
  96868. */
  96869. EffectLayer.prototype._rebuild = function () {
  96870. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96871. if (vb) {
  96872. vb._rebuild();
  96873. }
  96874. this._generateIndexBuffer();
  96875. };
  96876. /**
  96877. * Dispose only the render target textures and post process.
  96878. */
  96879. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96880. this._mainTexture.dispose();
  96881. for (var i = 0; i < this._postProcesses.length; i++) {
  96882. if (this._postProcesses[i]) {
  96883. this._postProcesses[i].dispose();
  96884. }
  96885. }
  96886. this._postProcesses = [];
  96887. for (var i = 0; i < this._textures.length; i++) {
  96888. if (this._textures[i]) {
  96889. this._textures[i].dispose();
  96890. }
  96891. }
  96892. this._textures = [];
  96893. };
  96894. /**
  96895. * Dispose the highlight layer and free resources.
  96896. */
  96897. EffectLayer.prototype.dispose = function () {
  96898. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96899. if (vertexBuffer) {
  96900. vertexBuffer.dispose();
  96901. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96902. }
  96903. if (this._indexBuffer) {
  96904. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96905. this._indexBuffer = null;
  96906. }
  96907. // Clean textures and post processes
  96908. this._disposeTextureAndPostProcesses();
  96909. // Remove from scene
  96910. var index = this._scene.effectLayers.indexOf(this, 0);
  96911. if (index > -1) {
  96912. this._scene.effectLayers.splice(index, 1);
  96913. }
  96914. // Callback
  96915. this.onDisposeObservable.notifyObservers(this);
  96916. this.onDisposeObservable.clear();
  96917. this.onBeforeRenderMainTextureObservable.clear();
  96918. this.onBeforeComposeObservable.clear();
  96919. this.onAfterComposeObservable.clear();
  96920. this.onSizeChangedObservable.clear();
  96921. };
  96922. /**
  96923. * Gets the class name of the effect layer
  96924. * @returns the string with the class name of the effect layer
  96925. */
  96926. EffectLayer.prototype.getClassName = function () {
  96927. return "EffectLayer";
  96928. };
  96929. /**
  96930. * Creates an effect layer from parsed effect layer data
  96931. * @param parsedEffectLayer defines effect layer data
  96932. * @param scene defines the current scene
  96933. * @param rootUrl defines the root URL containing the effect layer information
  96934. * @returns a parsed effect Layer
  96935. */
  96936. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96937. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96938. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96939. };
  96940. __decorate([
  96941. BABYLON.serialize()
  96942. ], EffectLayer.prototype, "name", void 0);
  96943. __decorate([
  96944. BABYLON.serializeAsColor4()
  96945. ], EffectLayer.prototype, "neutralColor", void 0);
  96946. __decorate([
  96947. BABYLON.serialize()
  96948. ], EffectLayer.prototype, "isEnabled", void 0);
  96949. __decorate([
  96950. BABYLON.serializeAsCameraReference()
  96951. ], EffectLayer.prototype, "camera", null);
  96952. __decorate([
  96953. BABYLON.serialize()
  96954. ], EffectLayer.prototype, "renderingGroupId", null);
  96955. return EffectLayer;
  96956. }());
  96957. BABYLON.EffectLayer = EffectLayer;
  96958. })(BABYLON || (BABYLON = {}));
  96959. //# sourceMappingURL=babylon.effectLayer.js.map
  96960. var BABYLON;
  96961. (function (BABYLON) {
  96962. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96963. for (var index = 0; index < this.effectLayers.length; index++) {
  96964. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96965. return this.effectLayers[index];
  96966. }
  96967. }
  96968. return null;
  96969. };
  96970. /**
  96971. * Special Glow Blur post process only blurring the alpha channel
  96972. * It enforces keeping the most luminous color in the color channel.
  96973. */
  96974. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96975. __extends(GlowBlurPostProcess, _super);
  96976. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96978. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96979. _this.direction = direction;
  96980. _this.kernel = kernel;
  96981. _this.onApplyObservable.add(function (effect) {
  96982. effect.setFloat2("screenSize", _this.width, _this.height);
  96983. effect.setVector2("direction", _this.direction);
  96984. effect.setFloat("blurWidth", _this.kernel);
  96985. });
  96986. return _this;
  96987. }
  96988. return GlowBlurPostProcess;
  96989. }(BABYLON.PostProcess));
  96990. /**
  96991. * The highlight layer Helps adding a glow effect around a mesh.
  96992. *
  96993. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96994. * glowy meshes to your scene.
  96995. *
  96996. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96997. */
  96998. var HighlightLayer = /** @class */ (function (_super) {
  96999. __extends(HighlightLayer, _super);
  97000. /**
  97001. * Instantiates a new highlight Layer and references it to the scene..
  97002. * @param name The name of the layer
  97003. * @param scene The scene to use the layer in
  97004. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  97005. */
  97006. function HighlightLayer(name, scene, options) {
  97007. var _this = _super.call(this, name, scene) || this;
  97008. _this.name = name;
  97009. /**
  97010. * Specifies whether or not the inner glow is ACTIVE in the layer.
  97011. */
  97012. _this.innerGlow = true;
  97013. /**
  97014. * Specifies whether or not the outer glow is ACTIVE in the layer.
  97015. */
  97016. _this.outerGlow = true;
  97017. /**
  97018. * An event triggered when the highlight layer is being blurred.
  97019. */
  97020. _this.onBeforeBlurObservable = new BABYLON.Observable();
  97021. /**
  97022. * An event triggered when the highlight layer has been blurred.
  97023. */
  97024. _this.onAfterBlurObservable = new BABYLON.Observable();
  97025. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  97026. _this._meshes = {};
  97027. _this._excludedMeshes = {};
  97028. _this.neutralColor = HighlightLayer.NeutralColor;
  97029. // Warn on stencil
  97030. if (!_this._engine.isStencilEnable) {
  97031. 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 }");
  97032. }
  97033. // Adapt options
  97034. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  97035. // Initialize the layer
  97036. _this._init({
  97037. alphaBlendingMode: _this._options.alphaBlendingMode,
  97038. camera: _this._options.camera,
  97039. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97040. mainTextureRatio: _this._options.mainTextureRatio,
  97041. renderingGroupId: _this._options.renderingGroupId
  97042. });
  97043. // Do not render as long as no meshes have been added
  97044. _this._shouldRender = false;
  97045. return _this;
  97046. }
  97047. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  97048. /**
  97049. * Gets the horizontal size of the blur.
  97050. */
  97051. get: function () {
  97052. return this._horizontalBlurPostprocess.kernel;
  97053. },
  97054. /**
  97055. * Specifies the horizontal size of the blur.
  97056. */
  97057. set: function (value) {
  97058. this._horizontalBlurPostprocess.kernel = value;
  97059. },
  97060. enumerable: true,
  97061. configurable: true
  97062. });
  97063. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  97064. /**
  97065. * Gets the vertical size of the blur.
  97066. */
  97067. get: function () {
  97068. return this._verticalBlurPostprocess.kernel;
  97069. },
  97070. /**
  97071. * Specifies the vertical size of the blur.
  97072. */
  97073. set: function (value) {
  97074. this._verticalBlurPostprocess.kernel = value;
  97075. },
  97076. enumerable: true,
  97077. configurable: true
  97078. });
  97079. /**
  97080. * Get the effect name of the layer.
  97081. * @return The effect name
  97082. */
  97083. HighlightLayer.prototype.getEffectName = function () {
  97084. return HighlightLayer.EffectName;
  97085. };
  97086. /**
  97087. * Create the merge effect. This is the shader use to blit the information back
  97088. * to the main canvas at the end of the scene rendering.
  97089. */
  97090. HighlightLayer.prototype._createMergeEffect = function () {
  97091. // Effect
  97092. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  97093. };
  97094. /**
  97095. * Creates the render target textures and post processes used in the highlight layer.
  97096. */
  97097. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  97098. var _this = this;
  97099. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  97100. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  97101. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97102. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97103. var textureType = 0;
  97104. if (this._engine.getCaps().textureHalfFloatRender) {
  97105. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97106. }
  97107. else {
  97108. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97109. }
  97110. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  97111. width: blurTextureWidth,
  97112. height: blurTextureHeight
  97113. }, this._scene, false, true, textureType);
  97114. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97115. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97116. this._blurTexture.anisotropicFilteringLevel = 16;
  97117. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  97118. this._blurTexture.renderParticles = false;
  97119. this._blurTexture.ignoreCameraViewport = true;
  97120. this._textures = [this._blurTexture];
  97121. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  97122. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97123. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  97124. effect.setTexture("textureSampler", _this._mainTexture);
  97125. });
  97126. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97127. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97128. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97129. });
  97130. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  97131. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  97132. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  97133. });
  97134. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97135. }
  97136. else {
  97137. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  97138. width: blurTextureWidth,
  97139. height: blurTextureHeight
  97140. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97141. this._horizontalBlurPostprocess.width = blurTextureWidth;
  97142. this._horizontalBlurPostprocess.height = blurTextureHeight;
  97143. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  97144. effect.setTexture("textureSampler", _this._mainTexture);
  97145. });
  97146. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  97147. width: blurTextureWidth,
  97148. height: blurTextureHeight
  97149. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97150. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  97151. }
  97152. this._mainTexture.onAfterUnbindObservable.add(function () {
  97153. _this.onBeforeBlurObservable.notifyObservers(_this);
  97154. var internalTexture = _this._blurTexture.getInternalTexture();
  97155. if (internalTexture) {
  97156. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  97157. }
  97158. _this.onAfterBlurObservable.notifyObservers(_this);
  97159. });
  97160. // Prevent autoClear.
  97161. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97162. };
  97163. /**
  97164. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97165. */
  97166. HighlightLayer.prototype.needStencil = function () {
  97167. return true;
  97168. };
  97169. /**
  97170. * Checks for the readiness of the element composing the layer.
  97171. * @param subMesh the mesh to check for
  97172. * @param useInstances specify wether or not to use instances to render the mesh
  97173. * @param emissiveTexture the associated emissive texture used to generate the glow
  97174. * @return true if ready otherwise, false
  97175. */
  97176. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  97177. var material = subMesh.getMaterial();
  97178. var mesh = subMesh.getRenderingMesh();
  97179. if (!material || !mesh || !this._meshes) {
  97180. return false;
  97181. }
  97182. var emissiveTexture = null;
  97183. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97184. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97185. emissiveTexture = material.emissiveTexture;
  97186. }
  97187. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97188. };
  97189. /**
  97190. * Implementation specific of rendering the generating effect on the main canvas.
  97191. * @param effect The effect used to render through
  97192. */
  97193. HighlightLayer.prototype._internalRender = function (effect) {
  97194. // Texture
  97195. effect.setTexture("textureSampler", this._blurTexture);
  97196. // Cache
  97197. var engine = this._engine;
  97198. var previousStencilBuffer = engine.getStencilBuffer();
  97199. var previousStencilFunction = engine.getStencilFunction();
  97200. var previousStencilMask = engine.getStencilMask();
  97201. var previousStencilOperationPass = engine.getStencilOperationPass();
  97202. var previousStencilOperationFail = engine.getStencilOperationFail();
  97203. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  97204. var previousStencilReference = engine.getStencilFunctionReference();
  97205. // Stencil operations
  97206. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  97207. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  97208. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  97209. // Draw order
  97210. engine.setStencilMask(0x00);
  97211. engine.setStencilBuffer(true);
  97212. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  97213. // 2 passes inner outer
  97214. if (this.outerGlow) {
  97215. effect.setFloat("offset", 0);
  97216. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  97217. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97218. }
  97219. if (this.innerGlow) {
  97220. effect.setFloat("offset", 1);
  97221. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  97222. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97223. }
  97224. // Restore Cache
  97225. engine.setStencilFunction(previousStencilFunction);
  97226. engine.setStencilMask(previousStencilMask);
  97227. engine.setStencilBuffer(previousStencilBuffer);
  97228. engine.setStencilOperationPass(previousStencilOperationPass);
  97229. engine.setStencilOperationFail(previousStencilOperationFail);
  97230. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  97231. engine.setStencilFunctionReference(previousStencilReference);
  97232. };
  97233. /**
  97234. * Returns true if the layer contains information to display, otherwise false.
  97235. */
  97236. HighlightLayer.prototype.shouldRender = function () {
  97237. if (_super.prototype.shouldRender.call(this)) {
  97238. return this._meshes ? true : false;
  97239. }
  97240. return false;
  97241. };
  97242. /**
  97243. * Returns true if the mesh should render, otherwise false.
  97244. * @param mesh The mesh to render
  97245. * @returns true if it should render otherwise false
  97246. */
  97247. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  97248. // Excluded Mesh
  97249. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  97250. return false;
  97251. }
  97252. ;
  97253. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97254. return false;
  97255. }
  97256. return true;
  97257. };
  97258. /**
  97259. * Sets the required values for both the emissive texture and and the main color.
  97260. */
  97261. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97262. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  97263. if (highlightLayerMesh) {
  97264. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  97265. }
  97266. else {
  97267. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97268. }
  97269. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  97270. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97271. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  97272. }
  97273. else {
  97274. this._emissiveTextureAndColor.texture = null;
  97275. }
  97276. };
  97277. /**
  97278. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  97279. * @param mesh The mesh to exclude from the highlight layer
  97280. */
  97281. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  97282. if (!this._excludedMeshes) {
  97283. return;
  97284. }
  97285. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97286. if (!meshExcluded) {
  97287. this._excludedMeshes[mesh.uniqueId] = {
  97288. mesh: mesh,
  97289. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  97290. mesh.getEngine().setStencilBuffer(false);
  97291. }),
  97292. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  97293. mesh.getEngine().setStencilBuffer(true);
  97294. }),
  97295. };
  97296. }
  97297. };
  97298. /**
  97299. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  97300. * @param mesh The mesh to highlight
  97301. */
  97302. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  97303. if (!this._excludedMeshes) {
  97304. return;
  97305. }
  97306. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  97307. if (meshExcluded) {
  97308. if (meshExcluded.beforeRender) {
  97309. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  97310. }
  97311. if (meshExcluded.afterRender) {
  97312. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  97313. }
  97314. }
  97315. this._excludedMeshes[mesh.uniqueId] = null;
  97316. };
  97317. /**
  97318. * Determine if a given mesh will be highlighted by the current HighlightLayer
  97319. * @param mesh mesh to test
  97320. * @returns true if the mesh will be highlighted by the current HighlightLayer
  97321. */
  97322. HighlightLayer.prototype.hasMesh = function (mesh) {
  97323. if (!this._meshes) {
  97324. return false;
  97325. }
  97326. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97327. return false;
  97328. }
  97329. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  97330. };
  97331. /**
  97332. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  97333. * @param mesh The mesh to highlight
  97334. * @param color The color of the highlight
  97335. * @param glowEmissiveOnly Extract the glow from the emissive texture
  97336. */
  97337. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  97338. var _this = this;
  97339. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  97340. if (!this._meshes) {
  97341. return;
  97342. }
  97343. var meshHighlight = this._meshes[mesh.uniqueId];
  97344. if (meshHighlight) {
  97345. meshHighlight.color = color;
  97346. }
  97347. else {
  97348. this._meshes[mesh.uniqueId] = {
  97349. mesh: mesh,
  97350. color: color,
  97351. // Lambda required for capture due to Observable this context
  97352. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  97353. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  97354. _this._defaultStencilReference(mesh);
  97355. }
  97356. else {
  97357. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  97358. }
  97359. }),
  97360. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  97361. glowEmissiveOnly: glowEmissiveOnly
  97362. };
  97363. mesh.onDisposeObservable.add(function () {
  97364. _this._disposeMesh(mesh);
  97365. });
  97366. }
  97367. this._shouldRender = true;
  97368. };
  97369. /**
  97370. * Remove a mesh from the highlight layer in order to make it stop glowing.
  97371. * @param mesh The mesh to highlight
  97372. */
  97373. HighlightLayer.prototype.removeMesh = function (mesh) {
  97374. if (!this._meshes) {
  97375. return;
  97376. }
  97377. var meshHighlight = this._meshes[mesh.uniqueId];
  97378. if (meshHighlight) {
  97379. if (meshHighlight.observerHighlight) {
  97380. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97381. }
  97382. if (meshHighlight.observerDefault) {
  97383. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97384. }
  97385. delete this._meshes[mesh.uniqueId];
  97386. }
  97387. this._shouldRender = false;
  97388. for (var meshHighlightToCheck in this._meshes) {
  97389. if (this._meshes[meshHighlightToCheck]) {
  97390. this._shouldRender = true;
  97391. break;
  97392. }
  97393. }
  97394. };
  97395. /**
  97396. * Force the stencil to the normal expected value for none glowing parts
  97397. */
  97398. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  97399. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  97400. };
  97401. /**
  97402. * Free any resources and references associated to a mesh.
  97403. * Internal use
  97404. * @param mesh The mesh to free.
  97405. */
  97406. HighlightLayer.prototype._disposeMesh = function (mesh) {
  97407. this.removeMesh(mesh);
  97408. this.removeExcludedMesh(mesh);
  97409. };
  97410. /**
  97411. * Dispose the highlight layer and free resources.
  97412. */
  97413. HighlightLayer.prototype.dispose = function () {
  97414. if (this._meshes) {
  97415. // Clean mesh references
  97416. for (var id in this._meshes) {
  97417. var meshHighlight = this._meshes[id];
  97418. if (meshHighlight && meshHighlight.mesh) {
  97419. if (meshHighlight.observerHighlight) {
  97420. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  97421. }
  97422. if (meshHighlight.observerDefault) {
  97423. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  97424. }
  97425. }
  97426. }
  97427. this._meshes = null;
  97428. }
  97429. if (this._excludedMeshes) {
  97430. for (var id in this._excludedMeshes) {
  97431. var meshHighlight = this._excludedMeshes[id];
  97432. if (meshHighlight) {
  97433. if (meshHighlight.beforeRender) {
  97434. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  97435. }
  97436. if (meshHighlight.afterRender) {
  97437. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97438. }
  97439. }
  97440. }
  97441. this._excludedMeshes = null;
  97442. }
  97443. _super.prototype.dispose.call(this);
  97444. };
  97445. /**
  97446. * Gets the class name of the effect layer
  97447. * @returns the string with the class name of the effect layer
  97448. */
  97449. HighlightLayer.prototype.getClassName = function () {
  97450. return "HighlightLayer";
  97451. };
  97452. /**
  97453. * Serializes this Highlight layer
  97454. * @returns a serialized Highlight layer object
  97455. */
  97456. HighlightLayer.prototype.serialize = function () {
  97457. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97458. serializationObject.customType = "BABYLON.HighlightLayer";
  97459. // Highlighted meshes
  97460. serializationObject.meshes = [];
  97461. if (this._meshes) {
  97462. for (var m in this._meshes) {
  97463. var mesh = this._meshes[m];
  97464. if (mesh) {
  97465. serializationObject.meshes.push({
  97466. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97467. color: mesh.color.asArray(),
  97468. meshId: mesh.mesh.id
  97469. });
  97470. }
  97471. }
  97472. }
  97473. // Excluded meshes
  97474. serializationObject.excludedMeshes = [];
  97475. if (this._excludedMeshes) {
  97476. for (var e in this._excludedMeshes) {
  97477. var excludedMesh = this._excludedMeshes[e];
  97478. if (excludedMesh) {
  97479. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97480. }
  97481. }
  97482. }
  97483. return serializationObject;
  97484. };
  97485. /**
  97486. * Creates a Highlight layer from parsed Highlight layer data
  97487. * @param parsedHightlightLayer defines the Highlight layer data
  97488. * @param scene defines the current scene
  97489. * @param rootUrl defines the root URL containing the Highlight layer information
  97490. * @returns a parsed Highlight layer
  97491. */
  97492. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97493. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97494. var index;
  97495. // Excluded meshes
  97496. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97497. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97498. if (mesh) {
  97499. hl.addExcludedMesh(mesh);
  97500. }
  97501. }
  97502. // Included meshes
  97503. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97504. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97505. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97506. if (mesh) {
  97507. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97508. }
  97509. }
  97510. return hl;
  97511. };
  97512. /**
  97513. * Effect Name of the highlight layer.
  97514. */
  97515. HighlightLayer.EffectName = "HighlightLayer";
  97516. /**
  97517. * The neutral color used during the preparation of the glow effect.
  97518. * This is black by default as the blend operation is a blend operation.
  97519. */
  97520. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97521. /**
  97522. * Stencil value used for glowing meshes.
  97523. */
  97524. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97525. /**
  97526. * Stencil value used for the other meshes in the scene.
  97527. */
  97528. HighlightLayer.NormalMeshStencilReference = 0x01;
  97529. __decorate([
  97530. BABYLON.serialize()
  97531. ], HighlightLayer.prototype, "innerGlow", void 0);
  97532. __decorate([
  97533. BABYLON.serialize()
  97534. ], HighlightLayer.prototype, "outerGlow", void 0);
  97535. __decorate([
  97536. BABYLON.serialize()
  97537. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97538. __decorate([
  97539. BABYLON.serialize()
  97540. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97541. __decorate([
  97542. BABYLON.serialize("options")
  97543. ], HighlightLayer.prototype, "_options", void 0);
  97544. return HighlightLayer;
  97545. }(BABYLON.EffectLayer));
  97546. BABYLON.HighlightLayer = HighlightLayer;
  97547. })(BABYLON || (BABYLON = {}));
  97548. //# sourceMappingURL=babylon.highlightLayer.js.map
  97549. var BABYLON;
  97550. (function (BABYLON) {
  97551. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97552. for (var index = 0; index < this.effectLayers.length; index++) {
  97553. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97554. return this.effectLayers[index];
  97555. }
  97556. }
  97557. return null;
  97558. };
  97559. /**
  97560. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97561. *
  97562. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97563. * glowy meshes to your scene.
  97564. *
  97565. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97566. */
  97567. var GlowLayer = /** @class */ (function (_super) {
  97568. __extends(GlowLayer, _super);
  97569. /**
  97570. * Instantiates a new glow Layer and references it to the scene.
  97571. * @param name The name of the layer
  97572. * @param scene The scene to use the layer in
  97573. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97574. */
  97575. function GlowLayer(name, scene, options) {
  97576. var _this = _super.call(this, name, scene) || this;
  97577. _this._intensity = 1.0;
  97578. _this._includedOnlyMeshes = [];
  97579. _this._excludedMeshes = [];
  97580. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97581. // Adapt options
  97582. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  97583. // Initialize the layer
  97584. _this._init({
  97585. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97586. camera: _this._options.camera,
  97587. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97588. mainTextureRatio: _this._options.mainTextureRatio,
  97589. renderingGroupId: _this._options.renderingGroupId
  97590. });
  97591. return _this;
  97592. }
  97593. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97594. /**
  97595. * Gets the kernel size of the blur.
  97596. */
  97597. get: function () {
  97598. return this._horizontalBlurPostprocess1.kernel;
  97599. },
  97600. /**
  97601. * Sets the kernel size of the blur.
  97602. */
  97603. set: function (value) {
  97604. this._horizontalBlurPostprocess1.kernel = value;
  97605. this._verticalBlurPostprocess1.kernel = value;
  97606. this._horizontalBlurPostprocess2.kernel = value;
  97607. this._verticalBlurPostprocess2.kernel = value;
  97608. },
  97609. enumerable: true,
  97610. configurable: true
  97611. });
  97612. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97613. /**
  97614. * Gets the glow intensity.
  97615. */
  97616. get: function () {
  97617. return this._intensity;
  97618. },
  97619. /**
  97620. * Sets the glow intensity.
  97621. */
  97622. set: function (value) {
  97623. this._intensity = value;
  97624. },
  97625. enumerable: true,
  97626. configurable: true
  97627. });
  97628. /**
  97629. * Get the effect name of the layer.
  97630. * @return The effect name
  97631. */
  97632. GlowLayer.prototype.getEffectName = function () {
  97633. return GlowLayer.EffectName;
  97634. };
  97635. /**
  97636. * Create the merge effect. This is the shader use to blit the information back
  97637. * to the main canvas at the end of the scene rendering.
  97638. */
  97639. GlowLayer.prototype._createMergeEffect = function () {
  97640. // Effect
  97641. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97642. };
  97643. /**
  97644. * Creates the render target textures and post processes used in the glow layer.
  97645. */
  97646. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97647. var _this = this;
  97648. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97649. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97650. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97651. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97652. var textureType = 0;
  97653. if (this._engine.getCaps().textureHalfFloatRender) {
  97654. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97655. }
  97656. else {
  97657. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97658. }
  97659. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97660. width: blurTextureWidth,
  97661. height: blurTextureHeight
  97662. }, this._scene, false, true, textureType);
  97663. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97664. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97665. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97666. this._blurTexture1.renderParticles = false;
  97667. this._blurTexture1.ignoreCameraViewport = true;
  97668. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97669. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97670. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97671. width: blurTextureWidth2,
  97672. height: blurTextureHeight2
  97673. }, this._scene, false, true, textureType);
  97674. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97675. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97676. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97677. this._blurTexture2.renderParticles = false;
  97678. this._blurTexture2.ignoreCameraViewport = true;
  97679. this._textures = [this._blurTexture1, this._blurTexture2];
  97680. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97681. width: blurTextureWidth,
  97682. height: blurTextureHeight
  97683. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97684. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97685. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97686. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97687. effect.setTexture("textureSampler", _this._mainTexture);
  97688. });
  97689. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97690. width: blurTextureWidth,
  97691. height: blurTextureHeight
  97692. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97693. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97694. width: blurTextureWidth2,
  97695. height: blurTextureHeight2
  97696. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97697. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97698. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97699. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97700. effect.setTexture("textureSampler", _this._blurTexture1);
  97701. });
  97702. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97703. width: blurTextureWidth2,
  97704. height: blurTextureHeight2
  97705. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97706. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97707. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97708. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97709. this._mainTexture.samples = this._options.mainTextureSamples;
  97710. this._mainTexture.onAfterUnbindObservable.add(function () {
  97711. var internalTexture = _this._blurTexture1.getInternalTexture();
  97712. if (internalTexture) {
  97713. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97714. internalTexture = _this._blurTexture2.getInternalTexture();
  97715. if (internalTexture) {
  97716. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97717. }
  97718. }
  97719. });
  97720. // Prevent autoClear.
  97721. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97722. };
  97723. /**
  97724. * Checks for the readiness of the element composing the layer.
  97725. * @param subMesh the mesh to check for
  97726. * @param useInstances specify wether or not to use instances to render the mesh
  97727. * @param emissiveTexture the associated emissive texture used to generate the glow
  97728. * @return true if ready otherwise, false
  97729. */
  97730. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97731. var material = subMesh.getMaterial();
  97732. var mesh = subMesh.getRenderingMesh();
  97733. if (!material || !mesh) {
  97734. return false;
  97735. }
  97736. var emissiveTexture = material.emissiveTexture;
  97737. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97738. };
  97739. /**
  97740. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97741. */
  97742. GlowLayer.prototype.needStencil = function () {
  97743. return false;
  97744. };
  97745. /**
  97746. * Implementation specific of rendering the generating effect on the main canvas.
  97747. * @param effect The effect used to render through
  97748. */
  97749. GlowLayer.prototype._internalRender = function (effect) {
  97750. // Texture
  97751. effect.setTexture("textureSampler", this._blurTexture1);
  97752. effect.setTexture("textureSampler2", this._blurTexture2);
  97753. effect.setFloat("offset", this._intensity);
  97754. // Cache
  97755. var engine = this._engine;
  97756. var previousStencilBuffer = engine.getStencilBuffer();
  97757. // Draw order
  97758. engine.setStencilBuffer(false);
  97759. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97760. // Draw order
  97761. engine.setStencilBuffer(previousStencilBuffer);
  97762. };
  97763. /**
  97764. * Sets the required values for both the emissive texture and and the main color.
  97765. */
  97766. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97767. var textureLevel = 1.0;
  97768. if (this.customEmissiveTextureSelector) {
  97769. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97770. }
  97771. else {
  97772. if (material) {
  97773. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97774. if (this._emissiveTextureAndColor.texture) {
  97775. textureLevel = this._emissiveTextureAndColor.texture.level;
  97776. }
  97777. }
  97778. else {
  97779. this._emissiveTextureAndColor.texture = null;
  97780. }
  97781. }
  97782. if (this.customEmissiveColorSelector) {
  97783. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97784. }
  97785. else {
  97786. if (material.emissiveColor) {
  97787. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97788. }
  97789. else {
  97790. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97791. }
  97792. }
  97793. };
  97794. /**
  97795. * Returns true if the mesh should render, otherwise false.
  97796. * @param mesh The mesh to render
  97797. * @returns true if it should render otherwise false
  97798. */
  97799. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97800. return this.hasMesh(mesh);
  97801. };
  97802. /**
  97803. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97804. * @param mesh The mesh to exclude from the glow layer
  97805. */
  97806. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97807. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97808. this._excludedMeshes.push(mesh.uniqueId);
  97809. }
  97810. };
  97811. /**
  97812. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97813. * @param mesh The mesh to remove
  97814. */
  97815. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97816. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97817. if (index !== -1) {
  97818. this._excludedMeshes.splice(index, 1);
  97819. }
  97820. };
  97821. /**
  97822. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97823. * @param mesh The mesh to include in the glow layer
  97824. */
  97825. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97826. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97827. this._includedOnlyMeshes.push(mesh.uniqueId);
  97828. }
  97829. };
  97830. /**
  97831. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97832. * @param mesh The mesh to remove
  97833. */
  97834. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97835. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97836. if (index !== -1) {
  97837. this._includedOnlyMeshes.splice(index, 1);
  97838. }
  97839. };
  97840. /**
  97841. * Determine if a given mesh will be used in the glow layer
  97842. * @param mesh The mesh to test
  97843. * @returns true if the mesh will be highlighted by the current glow layer
  97844. */
  97845. GlowLayer.prototype.hasMesh = function (mesh) {
  97846. if (!_super.prototype.hasMesh.call(this, mesh)) {
  97847. return false;
  97848. }
  97849. // Included Mesh
  97850. if (this._includedOnlyMeshes.length) {
  97851. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97852. }
  97853. ;
  97854. // Excluded Mesh
  97855. if (this._excludedMeshes.length) {
  97856. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97857. }
  97858. ;
  97859. return true;
  97860. };
  97861. /**
  97862. * Free any resources and references associated to a mesh.
  97863. * Internal use
  97864. * @param mesh The mesh to free.
  97865. */
  97866. GlowLayer.prototype._disposeMesh = function (mesh) {
  97867. this.removeIncludedOnlyMesh(mesh);
  97868. this.removeExcludedMesh(mesh);
  97869. };
  97870. /**
  97871. * Gets the class name of the effect layer
  97872. * @returns the string with the class name of the effect layer
  97873. */
  97874. GlowLayer.prototype.getClassName = function () {
  97875. return "GlowLayer";
  97876. };
  97877. /**
  97878. * Serializes this glow layer
  97879. * @returns a serialized glow layer object
  97880. */
  97881. GlowLayer.prototype.serialize = function () {
  97882. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97883. serializationObject.customType = "BABYLON.GlowLayer";
  97884. var index;
  97885. // Included meshes
  97886. serializationObject.includedMeshes = [];
  97887. if (this._includedOnlyMeshes.length) {
  97888. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97889. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97890. if (mesh) {
  97891. serializationObject.includedMeshes.push(mesh.id);
  97892. }
  97893. }
  97894. }
  97895. // Excluded meshes
  97896. serializationObject.excludedMeshes = [];
  97897. if (this._excludedMeshes.length) {
  97898. for (index = 0; index < this._excludedMeshes.length; index++) {
  97899. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97900. if (mesh) {
  97901. serializationObject.excludedMeshes.push(mesh.id);
  97902. }
  97903. }
  97904. }
  97905. return serializationObject;
  97906. };
  97907. /**
  97908. * Creates a Glow Layer from parsed glow layer data
  97909. * @param parsedGlowLayer defines glow layer data
  97910. * @param scene defines the current scene
  97911. * @param rootUrl defines the root URL containing the glow layer information
  97912. * @returns a parsed Glow Layer
  97913. */
  97914. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97915. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97916. var index;
  97917. // Excluded meshes
  97918. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97919. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97920. if (mesh) {
  97921. gl.addExcludedMesh(mesh);
  97922. }
  97923. }
  97924. // Included meshes
  97925. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97926. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97927. if (mesh) {
  97928. gl.addIncludedOnlyMesh(mesh);
  97929. }
  97930. }
  97931. return gl;
  97932. };
  97933. /**
  97934. * Effect Name of the layer.
  97935. */
  97936. GlowLayer.EffectName = "GlowLayer";
  97937. /**
  97938. * The default blur kernel size used for the glow.
  97939. */
  97940. GlowLayer.DefaultBlurKernelSize = 32;
  97941. /**
  97942. * The default texture size ratio used for the glow.
  97943. */
  97944. GlowLayer.DefaultTextureRatio = 0.5;
  97945. __decorate([
  97946. BABYLON.serialize()
  97947. ], GlowLayer.prototype, "blurKernelSize", null);
  97948. __decorate([
  97949. BABYLON.serialize()
  97950. ], GlowLayer.prototype, "intensity", null);
  97951. __decorate([
  97952. BABYLON.serialize("options")
  97953. ], GlowLayer.prototype, "_options", void 0);
  97954. return GlowLayer;
  97955. }(BABYLON.EffectLayer));
  97956. BABYLON.GlowLayer = GlowLayer;
  97957. })(BABYLON || (BABYLON = {}));
  97958. //# sourceMappingURL=babylon.glowLayer.js.map
  97959. var BABYLON;
  97960. (function (BABYLON) {
  97961. /**
  97962. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97963. */
  97964. var AssetTaskState;
  97965. (function (AssetTaskState) {
  97966. /**
  97967. * Initialization
  97968. */
  97969. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97970. /**
  97971. * Running
  97972. */
  97973. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97974. /**
  97975. * Done
  97976. */
  97977. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97978. /**
  97979. * Error
  97980. */
  97981. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97982. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97983. /**
  97984. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97985. */
  97986. var AbstractAssetTask = /** @class */ (function () {
  97987. /**
  97988. * Creates a new {BABYLON.AssetsManager}
  97989. * @param name defines the name of the task
  97990. */
  97991. function AbstractAssetTask(
  97992. /**
  97993. * Task name
  97994. */ name) {
  97995. this.name = name;
  97996. this._isCompleted = false;
  97997. this._taskState = AssetTaskState.INIT;
  97998. }
  97999. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  98000. /**
  98001. * Get if the task is completed
  98002. */
  98003. get: function () {
  98004. return this._isCompleted;
  98005. },
  98006. enumerable: true,
  98007. configurable: true
  98008. });
  98009. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  98010. /**
  98011. * Gets the current state of the task
  98012. */
  98013. get: function () {
  98014. return this._taskState;
  98015. },
  98016. enumerable: true,
  98017. configurable: true
  98018. });
  98019. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  98020. /**
  98021. * Gets the current error object (if task is in error)
  98022. */
  98023. get: function () {
  98024. return this._errorObject;
  98025. },
  98026. enumerable: true,
  98027. configurable: true
  98028. });
  98029. /**
  98030. * Internal only
  98031. * @hidden
  98032. */
  98033. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  98034. if (this._errorObject) {
  98035. return;
  98036. }
  98037. this._errorObject = {
  98038. message: message,
  98039. exception: exception
  98040. };
  98041. };
  98042. /**
  98043. * Execute the current task
  98044. * @param scene defines the scene where you want your assets to be loaded
  98045. * @param onSuccess is a callback called when the task is successfully executed
  98046. * @param onError is a callback called if an error occurs
  98047. */
  98048. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98049. var _this = this;
  98050. this._taskState = AssetTaskState.RUNNING;
  98051. this.runTask(scene, function () {
  98052. _this.onDoneCallback(onSuccess, onError);
  98053. }, function (msg, exception) {
  98054. _this.onErrorCallback(onError, msg, exception);
  98055. });
  98056. };
  98057. /**
  98058. * Execute the current task
  98059. * @param scene defines the scene where you want your assets to be loaded
  98060. * @param onSuccess is a callback called when the task is successfully executed
  98061. * @param onError is a callback called if an error occurs
  98062. */
  98063. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98064. throw new Error("runTask is not implemented");
  98065. };
  98066. /**
  98067. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  98068. * This can be used with failed tasks that have the reason for failure fixed.
  98069. */
  98070. AbstractAssetTask.prototype.reset = function () {
  98071. this._taskState = AssetTaskState.INIT;
  98072. };
  98073. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  98074. this._taskState = AssetTaskState.ERROR;
  98075. this._errorObject = {
  98076. message: message,
  98077. exception: exception
  98078. };
  98079. if (this.onError) {
  98080. this.onError(this, message, exception);
  98081. }
  98082. onError();
  98083. };
  98084. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  98085. try {
  98086. this._taskState = AssetTaskState.DONE;
  98087. this._isCompleted = true;
  98088. if (this.onSuccess) {
  98089. this.onSuccess(this);
  98090. }
  98091. onSuccess();
  98092. }
  98093. catch (e) {
  98094. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  98095. }
  98096. };
  98097. return AbstractAssetTask;
  98098. }());
  98099. BABYLON.AbstractAssetTask = AbstractAssetTask;
  98100. /**
  98101. * Class used to share progress information about assets loading
  98102. */
  98103. var AssetsProgressEvent = /** @class */ (function () {
  98104. /**
  98105. * Creates a {BABYLON.AssetsProgressEvent}
  98106. * @param remainingCount defines the number of remaining tasks to process
  98107. * @param totalCount defines the total number of tasks
  98108. * @param task defines the task that was just processed
  98109. */
  98110. function AssetsProgressEvent(remainingCount, totalCount, task) {
  98111. this.remainingCount = remainingCount;
  98112. this.totalCount = totalCount;
  98113. this.task = task;
  98114. }
  98115. return AssetsProgressEvent;
  98116. }());
  98117. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  98118. /**
  98119. * Define a task used by {BABYLON.AssetsManager} to load meshes
  98120. */
  98121. var MeshAssetTask = /** @class */ (function (_super) {
  98122. __extends(MeshAssetTask, _super);
  98123. /**
  98124. * Creates a new {BABYLON.MeshAssetTask}
  98125. * @param name defines the name of the task
  98126. * @param meshesNames defines the list of mesh's names you want to load
  98127. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  98128. * @param sceneFilename defines the filename of the scene to load from
  98129. */
  98130. function MeshAssetTask(
  98131. /**
  98132. * Defines the name of the task
  98133. */
  98134. name,
  98135. /**
  98136. * Defines the list of mesh's names you want to load
  98137. */
  98138. meshesNames,
  98139. /**
  98140. * Defines the root url to use as a base to load your meshes and associated resources
  98141. */
  98142. rootUrl,
  98143. /**
  98144. * Defines the filename of the scene to load from
  98145. */
  98146. sceneFilename) {
  98147. var _this = _super.call(this, name) || this;
  98148. _this.name = name;
  98149. _this.meshesNames = meshesNames;
  98150. _this.rootUrl = rootUrl;
  98151. _this.sceneFilename = sceneFilename;
  98152. return _this;
  98153. }
  98154. /**
  98155. * Execute the current task
  98156. * @param scene defines the scene where you want your assets to be loaded
  98157. * @param onSuccess is a callback called when the task is successfully executed
  98158. * @param onError is a callback called if an error occurs
  98159. */
  98160. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98161. var _this = this;
  98162. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  98163. _this.loadedMeshes = meshes;
  98164. _this.loadedParticleSystems = particleSystems;
  98165. _this.loadedSkeletons = skeletons;
  98166. onSuccess();
  98167. }, null, function (scene, message, exception) {
  98168. onError(message, exception);
  98169. });
  98170. };
  98171. return MeshAssetTask;
  98172. }(AbstractAssetTask));
  98173. BABYLON.MeshAssetTask = MeshAssetTask;
  98174. /**
  98175. * Define a task used by {BABYLON.AssetsManager} to load text content
  98176. */
  98177. var TextFileAssetTask = /** @class */ (function (_super) {
  98178. __extends(TextFileAssetTask, _super);
  98179. /**
  98180. * Creates a new TextFileAssetTask object
  98181. * @param name defines the name of the task
  98182. * @param url defines the location of the file to load
  98183. */
  98184. function TextFileAssetTask(
  98185. /**
  98186. * Defines the name of the task
  98187. */
  98188. name,
  98189. /**
  98190. * Defines the location of the file to load
  98191. */
  98192. url) {
  98193. var _this = _super.call(this, name) || this;
  98194. _this.name = name;
  98195. _this.url = url;
  98196. return _this;
  98197. }
  98198. /**
  98199. * Execute the current task
  98200. * @param scene defines the scene where you want your assets to be loaded
  98201. * @param onSuccess is a callback called when the task is successfully executed
  98202. * @param onError is a callback called if an error occurs
  98203. */
  98204. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98205. var _this = this;
  98206. scene._loadFile(this.url, function (data) {
  98207. _this.text = data;
  98208. onSuccess();
  98209. }, undefined, false, false, function (request, exception) {
  98210. if (request) {
  98211. onError(request.status + " " + request.statusText, exception);
  98212. }
  98213. });
  98214. };
  98215. return TextFileAssetTask;
  98216. }(AbstractAssetTask));
  98217. BABYLON.TextFileAssetTask = TextFileAssetTask;
  98218. /**
  98219. * Define a task used by {BABYLON.AssetsManager} to load binary data
  98220. */
  98221. var BinaryFileAssetTask = /** @class */ (function (_super) {
  98222. __extends(BinaryFileAssetTask, _super);
  98223. /**
  98224. * Creates a new BinaryFileAssetTask object
  98225. * @param name defines the name of the new task
  98226. * @param url defines the location of the file to load
  98227. */
  98228. function BinaryFileAssetTask(
  98229. /**
  98230. * Defines the name of the task
  98231. */
  98232. name,
  98233. /**
  98234. * Defines the location of the file to load
  98235. */
  98236. url) {
  98237. var _this = _super.call(this, name) || this;
  98238. _this.name = name;
  98239. _this.url = url;
  98240. return _this;
  98241. }
  98242. /**
  98243. * Execute the current task
  98244. * @param scene defines the scene where you want your assets to be loaded
  98245. * @param onSuccess is a callback called when the task is successfully executed
  98246. * @param onError is a callback called if an error occurs
  98247. */
  98248. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98249. var _this = this;
  98250. scene._loadFile(this.url, function (data) {
  98251. _this.data = data;
  98252. onSuccess();
  98253. }, undefined, true, true, function (request, exception) {
  98254. if (request) {
  98255. onError(request.status + " " + request.statusText, exception);
  98256. }
  98257. });
  98258. };
  98259. return BinaryFileAssetTask;
  98260. }(AbstractAssetTask));
  98261. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  98262. /**
  98263. * Define a task used by {BABYLON.AssetsManager} to load images
  98264. */
  98265. var ImageAssetTask = /** @class */ (function (_super) {
  98266. __extends(ImageAssetTask, _super);
  98267. /**
  98268. * Creates a new ImageAssetTask
  98269. * @param name defines the name of the task
  98270. * @param url defines the location of the image to load
  98271. */
  98272. function ImageAssetTask(
  98273. /**
  98274. * Defines the name of the task
  98275. */
  98276. name,
  98277. /**
  98278. * Defines the location of the image to load
  98279. */
  98280. url) {
  98281. var _this = _super.call(this, name) || this;
  98282. _this.name = name;
  98283. _this.url = url;
  98284. return _this;
  98285. }
  98286. /**
  98287. * Execute the current task
  98288. * @param scene defines the scene where you want your assets to be loaded
  98289. * @param onSuccess is a callback called when the task is successfully executed
  98290. * @param onError is a callback called if an error occurs
  98291. */
  98292. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98293. var _this = this;
  98294. var img = new Image();
  98295. BABYLON.Tools.SetCorsBehavior(this.url, img);
  98296. img.onload = function () {
  98297. _this.image = img;
  98298. onSuccess();
  98299. };
  98300. img.onerror = function (err) {
  98301. onError("Error loading image", err);
  98302. };
  98303. img.src = this.url;
  98304. };
  98305. return ImageAssetTask;
  98306. }(AbstractAssetTask));
  98307. BABYLON.ImageAssetTask = ImageAssetTask;
  98308. /**
  98309. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  98310. */
  98311. var TextureAssetTask = /** @class */ (function (_super) {
  98312. __extends(TextureAssetTask, _super);
  98313. /**
  98314. * Creates a new TextureAssetTask object
  98315. * @param name defines the name of the task
  98316. * @param url defines the location of the file to load
  98317. * @param noMipmap defines if mipmap should not be generated (default is false)
  98318. * @param invertY defines if texture must be inverted on Y axis (default is false)
  98319. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98320. */
  98321. function TextureAssetTask(
  98322. /**
  98323. * Defines the name of the task
  98324. */
  98325. name,
  98326. /**
  98327. * Defines the location of the file to load
  98328. */
  98329. url,
  98330. /**
  98331. * Defines if mipmap should not be generated (default is false)
  98332. */
  98333. noMipmap,
  98334. /**
  98335. * Defines if texture must be inverted on Y axis (default is false)
  98336. */
  98337. invertY,
  98338. /**
  98339. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  98340. */
  98341. samplingMode) {
  98342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98343. var _this = _super.call(this, name) || this;
  98344. _this.name = name;
  98345. _this.url = url;
  98346. _this.noMipmap = noMipmap;
  98347. _this.invertY = invertY;
  98348. _this.samplingMode = samplingMode;
  98349. return _this;
  98350. }
  98351. /**
  98352. * Execute the current task
  98353. * @param scene defines the scene where you want your assets to be loaded
  98354. * @param onSuccess is a callback called when the task is successfully executed
  98355. * @param onError is a callback called if an error occurs
  98356. */
  98357. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98358. var onload = function () {
  98359. onSuccess();
  98360. };
  98361. var onerror = function (message, exception) {
  98362. onError(message, exception);
  98363. };
  98364. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  98365. };
  98366. return TextureAssetTask;
  98367. }(AbstractAssetTask));
  98368. BABYLON.TextureAssetTask = TextureAssetTask;
  98369. /**
  98370. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  98371. */
  98372. var CubeTextureAssetTask = /** @class */ (function (_super) {
  98373. __extends(CubeTextureAssetTask, _super);
  98374. /**
  98375. * Creates a new CubeTextureAssetTask
  98376. * @param name defines the name of the task
  98377. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98378. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98379. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98380. * @param files defines the explicit list of files (undefined by default)
  98381. */
  98382. function CubeTextureAssetTask(
  98383. /**
  98384. * Defines the name of the task
  98385. */
  98386. name,
  98387. /**
  98388. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  98389. */
  98390. url,
  98391. /**
  98392. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  98393. */
  98394. extensions,
  98395. /**
  98396. * Defines if mipmaps should not be generated (default is false)
  98397. */
  98398. noMipmap,
  98399. /**
  98400. * Defines the explicit list of files (undefined by default)
  98401. */
  98402. files) {
  98403. var _this = _super.call(this, name) || this;
  98404. _this.name = name;
  98405. _this.url = url;
  98406. _this.extensions = extensions;
  98407. _this.noMipmap = noMipmap;
  98408. _this.files = files;
  98409. return _this;
  98410. }
  98411. /**
  98412. * Execute the current task
  98413. * @param scene defines the scene where you want your assets to be loaded
  98414. * @param onSuccess is a callback called when the task is successfully executed
  98415. * @param onError is a callback called if an error occurs
  98416. */
  98417. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  98418. var onload = function () {
  98419. onSuccess();
  98420. };
  98421. var onerror = function (message, exception) {
  98422. onError(message, exception);
  98423. };
  98424. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  98425. };
  98426. return CubeTextureAssetTask;
  98427. }(AbstractAssetTask));
  98428. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  98429. /**
  98430. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  98431. */
  98432. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  98433. __extends(HDRCubeTextureAssetTask, _super);
  98434. /**
  98435. * Creates a new HDRCubeTextureAssetTask object
  98436. * @param name defines the name of the task
  98437. * @param url defines the location of the file to load
  98438. * @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.
  98439. * @param noMipmap defines if mipmaps should not be generated (default is false)
  98440. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98441. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  98442. * @param reserved Internal use only
  98443. */
  98444. function HDRCubeTextureAssetTask(
  98445. /**
  98446. * Defines the name of the task
  98447. */
  98448. name,
  98449. /**
  98450. * Defines the location of the file to load
  98451. */
  98452. url,
  98453. /**
  98454. * Defines the desired size (the more it increases the longer the generation will be)
  98455. */
  98456. size,
  98457. /**
  98458. * Defines if mipmaps should not be generated (default is false)
  98459. */
  98460. noMipmap,
  98461. /**
  98462. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98463. */
  98464. generateHarmonics,
  98465. /**
  98466. * 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)
  98467. */
  98468. gammaSpace,
  98469. /**
  98470. * Internal Use Only
  98471. */
  98472. reserved) {
  98473. if (noMipmap === void 0) { noMipmap = false; }
  98474. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98475. if (gammaSpace === void 0) { gammaSpace = false; }
  98476. if (reserved === void 0) { reserved = false; }
  98477. var _this = _super.call(this, name) || this;
  98478. _this.name = name;
  98479. _this.url = url;
  98480. _this.size = size;
  98481. _this.noMipmap = noMipmap;
  98482. _this.generateHarmonics = generateHarmonics;
  98483. _this.gammaSpace = gammaSpace;
  98484. _this.reserved = reserved;
  98485. return _this;
  98486. }
  98487. /**
  98488. * Execute the current task
  98489. * @param scene defines the scene where you want your assets to be loaded
  98490. * @param onSuccess is a callback called when the task is successfully executed
  98491. * @param onError is a callback called if an error occurs
  98492. */
  98493. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98494. var onload = function () {
  98495. onSuccess();
  98496. };
  98497. var onerror = function (message, exception) {
  98498. onError(message, exception);
  98499. };
  98500. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98501. };
  98502. return HDRCubeTextureAssetTask;
  98503. }(AbstractAssetTask));
  98504. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98505. /**
  98506. * This class can be used to easily import assets into a scene
  98507. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98508. */
  98509. var AssetsManager = /** @class */ (function () {
  98510. /**
  98511. * Creates a new AssetsManager
  98512. * @param scene defines the scene to work on
  98513. */
  98514. function AssetsManager(scene) {
  98515. this._isLoading = false;
  98516. this._tasks = new Array();
  98517. this._waitingTasksCount = 0;
  98518. this._totalTasksCount = 0;
  98519. /**
  98520. * Observable called when all tasks are processed
  98521. */
  98522. this.onTaskSuccessObservable = new BABYLON.Observable();
  98523. /**
  98524. * Observable called when a task had an error
  98525. */
  98526. this.onTaskErrorObservable = new BABYLON.Observable();
  98527. /**
  98528. * Observable called when a task is successful
  98529. */
  98530. this.onTasksDoneObservable = new BABYLON.Observable();
  98531. /**
  98532. * Observable called when a task is done (whatever the result is)
  98533. */
  98534. this.onProgressObservable = new BABYLON.Observable();
  98535. /**
  98536. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98537. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98538. */
  98539. this.useDefaultLoadingScreen = true;
  98540. this._scene = scene;
  98541. }
  98542. /**
  98543. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98544. * @param taskName defines the name of the new task
  98545. * @param meshesNames defines the name of meshes to load
  98546. * @param rootUrl defines the root url to use to locate files
  98547. * @param sceneFilename defines the filename of the scene file
  98548. * @returns a new {BABYLON.MeshAssetTask} object
  98549. */
  98550. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98551. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98552. this._tasks.push(task);
  98553. return task;
  98554. };
  98555. /**
  98556. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98557. * @param taskName defines the name of the new task
  98558. * @param url defines the url of the file to load
  98559. * @returns a new {BABYLON.TextFileAssetTask} object
  98560. */
  98561. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98562. var task = new TextFileAssetTask(taskName, url);
  98563. this._tasks.push(task);
  98564. return task;
  98565. };
  98566. /**
  98567. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98568. * @param taskName defines the name of the new task
  98569. * @param url defines the url of the file to load
  98570. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98571. */
  98572. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98573. var task = new BinaryFileAssetTask(taskName, url);
  98574. this._tasks.push(task);
  98575. return task;
  98576. };
  98577. /**
  98578. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98579. * @param taskName defines the name of the new task
  98580. * @param url defines the url of the file to load
  98581. * @returns a new {BABYLON.ImageAssetTask} object
  98582. */
  98583. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98584. var task = new ImageAssetTask(taskName, url);
  98585. this._tasks.push(task);
  98586. return task;
  98587. };
  98588. /**
  98589. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98590. * @param taskName defines the name of the new task
  98591. * @param url defines the url of the file to load
  98592. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98593. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98594. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98595. * @returns a new {BABYLON.TextureAssetTask} object
  98596. */
  98597. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98599. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98600. this._tasks.push(task);
  98601. return task;
  98602. };
  98603. /**
  98604. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98605. * @param taskName defines the name of the new task
  98606. * @param url defines the url of the file to load
  98607. * @param extensions defines the extension to use to load the cube map (can be null)
  98608. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98609. * @param files defines the list of files to load (can be null)
  98610. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98611. */
  98612. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98613. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98614. this._tasks.push(task);
  98615. return task;
  98616. };
  98617. /**
  98618. *
  98619. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98620. * @param taskName defines the name of the new task
  98621. * @param url defines the url of the file to load
  98622. * @param size defines the size you want for the cubemap (can be null)
  98623. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98624. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98625. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  98626. * @param reserved Internal use only
  98627. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98628. */
  98629. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98630. if (noMipmap === void 0) { noMipmap = false; }
  98631. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98632. if (gammaSpace === void 0) { gammaSpace = false; }
  98633. if (reserved === void 0) { reserved = false; }
  98634. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98635. this._tasks.push(task);
  98636. return task;
  98637. };
  98638. /**
  98639. * Remove a task from the assets manager.
  98640. * @param task the task to remove
  98641. */
  98642. AssetsManager.prototype.removeTask = function (task) {
  98643. var index = this._tasks.indexOf(task);
  98644. if (index > -1) {
  98645. this._tasks.splice(index, 1);
  98646. }
  98647. };
  98648. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98649. this._waitingTasksCount--;
  98650. try {
  98651. if (this.onProgress) {
  98652. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98653. }
  98654. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98655. }
  98656. catch (e) {
  98657. BABYLON.Tools.Error("Error running progress callbacks.");
  98658. console.log(e);
  98659. }
  98660. if (this._waitingTasksCount === 0) {
  98661. try {
  98662. if (this.onFinish) {
  98663. this.onFinish(this._tasks);
  98664. }
  98665. // Let's remove successfull tasks
  98666. var currentTasks = this._tasks.slice();
  98667. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98668. var task = currentTasks_1[_i];
  98669. if (task.taskState === AssetTaskState.DONE) {
  98670. var index = this._tasks.indexOf(task);
  98671. if (index > -1) {
  98672. this._tasks.splice(index, 1);
  98673. }
  98674. }
  98675. }
  98676. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98677. }
  98678. catch (e) {
  98679. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98680. console.log(e);
  98681. }
  98682. this._isLoading = false;
  98683. this._scene.getEngine().hideLoadingUI();
  98684. }
  98685. };
  98686. AssetsManager.prototype._runTask = function (task) {
  98687. var _this = this;
  98688. var done = function () {
  98689. try {
  98690. if (_this.onTaskSuccess) {
  98691. _this.onTaskSuccess(task);
  98692. }
  98693. _this.onTaskSuccessObservable.notifyObservers(task);
  98694. _this._decreaseWaitingTasksCount(task);
  98695. }
  98696. catch (e) {
  98697. error("Error executing task success callbacks", e);
  98698. }
  98699. };
  98700. var error = function (message, exception) {
  98701. task._setErrorObject(message, exception);
  98702. if (_this.onTaskError) {
  98703. _this.onTaskError(task);
  98704. }
  98705. _this.onTaskErrorObservable.notifyObservers(task);
  98706. _this._decreaseWaitingTasksCount(task);
  98707. };
  98708. task.run(this._scene, done, error);
  98709. };
  98710. /**
  98711. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98712. * @return the current instance of the {BABYLON.AssetsManager}
  98713. */
  98714. AssetsManager.prototype.reset = function () {
  98715. this._isLoading = false;
  98716. this._tasks = new Array();
  98717. return this;
  98718. };
  98719. /**
  98720. * Start the loading process
  98721. * @return the current instance of the {BABYLON.AssetsManager}
  98722. */
  98723. AssetsManager.prototype.load = function () {
  98724. if (this._isLoading) {
  98725. return this;
  98726. }
  98727. this._isLoading = true;
  98728. this._waitingTasksCount = this._tasks.length;
  98729. this._totalTasksCount = this._tasks.length;
  98730. if (this._waitingTasksCount === 0) {
  98731. this._isLoading = false;
  98732. if (this.onFinish) {
  98733. this.onFinish(this._tasks);
  98734. }
  98735. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98736. return this;
  98737. }
  98738. if (this.useDefaultLoadingScreen) {
  98739. this._scene.getEngine().displayLoadingUI();
  98740. }
  98741. for (var index = 0; index < this._tasks.length; index++) {
  98742. var task = this._tasks[index];
  98743. if (task.taskState === AssetTaskState.INIT) {
  98744. this._runTask(task);
  98745. }
  98746. }
  98747. return this;
  98748. };
  98749. return AssetsManager;
  98750. }());
  98751. BABYLON.AssetsManager = AssetsManager;
  98752. })(BABYLON || (BABYLON = {}));
  98753. //# sourceMappingURL=babylon.assetsManager.js.map
  98754. var BABYLON;
  98755. (function (BABYLON) {
  98756. var serializedGeometries = [];
  98757. var serializeGeometry = function (geometry, serializationGeometries) {
  98758. if (serializedGeometries[geometry.id]) {
  98759. return;
  98760. }
  98761. if (geometry.doNotSerialize) {
  98762. return;
  98763. }
  98764. if (geometry instanceof BABYLON.BoxGeometry) {
  98765. serializationGeometries.boxes.push(geometry.serialize());
  98766. }
  98767. else if (geometry instanceof BABYLON.SphereGeometry) {
  98768. serializationGeometries.spheres.push(geometry.serialize());
  98769. }
  98770. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98771. serializationGeometries.cylinders.push(geometry.serialize());
  98772. }
  98773. else if (geometry instanceof BABYLON.TorusGeometry) {
  98774. serializationGeometries.toruses.push(geometry.serialize());
  98775. }
  98776. else if (geometry instanceof BABYLON.GroundGeometry) {
  98777. serializationGeometries.grounds.push(geometry.serialize());
  98778. }
  98779. else if (geometry instanceof BABYLON.Plane) {
  98780. serializationGeometries.planes.push(geometry.serialize());
  98781. }
  98782. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98783. serializationGeometries.torusKnots.push(geometry.serialize());
  98784. }
  98785. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98786. throw new Error("Unknown primitive type");
  98787. }
  98788. else {
  98789. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98790. }
  98791. serializedGeometries[geometry.id] = true;
  98792. };
  98793. var serializeMesh = function (mesh, serializationScene) {
  98794. var serializationObject = {};
  98795. // Geometry
  98796. var geometry = mesh._geometry;
  98797. if (geometry) {
  98798. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98799. // 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
  98800. serializeGeometry(geometry, serializationScene.geometries);
  98801. }
  98802. }
  98803. // Custom
  98804. if (mesh.serialize) {
  98805. mesh.serialize(serializationObject);
  98806. }
  98807. return serializationObject;
  98808. };
  98809. var finalizeSingleMesh = function (mesh, serializationObject) {
  98810. //only works if the mesh is already loaded
  98811. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98812. //serialize material
  98813. if (mesh.material) {
  98814. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98815. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98816. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98817. serializationObject.multiMaterials.push(mesh.material.serialize());
  98818. }
  98819. }
  98820. else {
  98821. serializationObject.materials = serializationObject.materials || [];
  98822. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98823. serializationObject.materials.push(mesh.material.serialize());
  98824. }
  98825. }
  98826. }
  98827. //serialize geometry
  98828. var geometry = mesh._geometry;
  98829. if (geometry) {
  98830. if (!serializationObject.geometries) {
  98831. serializationObject.geometries = {};
  98832. serializationObject.geometries.boxes = [];
  98833. serializationObject.geometries.spheres = [];
  98834. serializationObject.geometries.cylinders = [];
  98835. serializationObject.geometries.toruses = [];
  98836. serializationObject.geometries.grounds = [];
  98837. serializationObject.geometries.planes = [];
  98838. serializationObject.geometries.torusKnots = [];
  98839. serializationObject.geometries.vertexData = [];
  98840. }
  98841. serializeGeometry(geometry, serializationObject.geometries);
  98842. }
  98843. // Skeletons
  98844. if (mesh.skeleton) {
  98845. serializationObject.skeletons = serializationObject.skeletons || [];
  98846. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98847. }
  98848. //serialize the actual mesh
  98849. serializationObject.meshes = serializationObject.meshes || [];
  98850. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98851. }
  98852. };
  98853. var SceneSerializer = /** @class */ (function () {
  98854. function SceneSerializer() {
  98855. }
  98856. SceneSerializer.ClearCache = function () {
  98857. serializedGeometries = [];
  98858. };
  98859. SceneSerializer.Serialize = function (scene) {
  98860. var serializationObject = {};
  98861. SceneSerializer.ClearCache();
  98862. // Scene
  98863. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98864. serializationObject.autoClear = scene.autoClear;
  98865. serializationObject.clearColor = scene.clearColor.asArray();
  98866. serializationObject.ambientColor = scene.ambientColor.asArray();
  98867. serializationObject.gravity = scene.gravity.asArray();
  98868. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98869. serializationObject.workerCollisions = scene.workerCollisions;
  98870. // Fog
  98871. if (scene.fogMode && scene.fogMode !== 0) {
  98872. serializationObject.fogMode = scene.fogMode;
  98873. serializationObject.fogColor = scene.fogColor.asArray();
  98874. serializationObject.fogStart = scene.fogStart;
  98875. serializationObject.fogEnd = scene.fogEnd;
  98876. serializationObject.fogDensity = scene.fogDensity;
  98877. }
  98878. //Physics
  98879. if (scene.isPhysicsEnabled()) {
  98880. var physicEngine = scene.getPhysicsEngine();
  98881. if (physicEngine) {
  98882. serializationObject.physicsEnabled = true;
  98883. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98884. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98885. }
  98886. }
  98887. // Metadata
  98888. if (scene.metadata) {
  98889. serializationObject.metadata = scene.metadata;
  98890. }
  98891. // Morph targets
  98892. serializationObject.morphTargetManagers = [];
  98893. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98894. var abstractMesh = _a[_i];
  98895. var manager = abstractMesh.morphTargetManager;
  98896. if (manager) {
  98897. serializationObject.morphTargetManagers.push(manager.serialize());
  98898. }
  98899. }
  98900. // Lights
  98901. serializationObject.lights = [];
  98902. var index;
  98903. var light;
  98904. for (index = 0; index < scene.lights.length; index++) {
  98905. light = scene.lights[index];
  98906. if (!light.doNotSerialize) {
  98907. serializationObject.lights.push(light.serialize());
  98908. }
  98909. }
  98910. // Cameras
  98911. serializationObject.cameras = [];
  98912. for (index = 0; index < scene.cameras.length; index++) {
  98913. var camera = scene.cameras[index];
  98914. if (!camera.doNotSerialize) {
  98915. serializationObject.cameras.push(camera.serialize());
  98916. }
  98917. }
  98918. if (scene.activeCamera) {
  98919. serializationObject.activeCameraID = scene.activeCamera.id;
  98920. }
  98921. // Animations
  98922. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98923. // Materials
  98924. serializationObject.materials = [];
  98925. serializationObject.multiMaterials = [];
  98926. var material;
  98927. for (index = 0; index < scene.materials.length; index++) {
  98928. material = scene.materials[index];
  98929. if (!material.doNotSerialize) {
  98930. serializationObject.materials.push(material.serialize());
  98931. }
  98932. }
  98933. // MultiMaterials
  98934. serializationObject.multiMaterials = [];
  98935. for (index = 0; index < scene.multiMaterials.length; index++) {
  98936. var multiMaterial = scene.multiMaterials[index];
  98937. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98938. }
  98939. // Environment texture
  98940. if (scene.environmentTexture) {
  98941. serializationObject.environmentTexture = scene.environmentTexture.name;
  98942. }
  98943. // Skeletons
  98944. serializationObject.skeletons = [];
  98945. for (index = 0; index < scene.skeletons.length; index++) {
  98946. var skeleton = scene.skeletons[index];
  98947. if (!skeleton.doNotSerialize) {
  98948. serializationObject.skeletons.push(skeleton.serialize());
  98949. }
  98950. }
  98951. // Transform nodes
  98952. serializationObject.transformNodes = [];
  98953. for (index = 0; index < scene.transformNodes.length; index++) {
  98954. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98955. }
  98956. // Geometries
  98957. serializationObject.geometries = {};
  98958. serializationObject.geometries.boxes = [];
  98959. serializationObject.geometries.spheres = [];
  98960. serializationObject.geometries.cylinders = [];
  98961. serializationObject.geometries.toruses = [];
  98962. serializationObject.geometries.grounds = [];
  98963. serializationObject.geometries.planes = [];
  98964. serializationObject.geometries.torusKnots = [];
  98965. serializationObject.geometries.vertexData = [];
  98966. serializedGeometries = [];
  98967. var geometries = scene.getGeometries();
  98968. for (index = 0; index < geometries.length; index++) {
  98969. var geometry = geometries[index];
  98970. if (geometry.isReady()) {
  98971. serializeGeometry(geometry, serializationObject.geometries);
  98972. }
  98973. }
  98974. // Meshes
  98975. serializationObject.meshes = [];
  98976. for (index = 0; index < scene.meshes.length; index++) {
  98977. var abstractMesh = scene.meshes[index];
  98978. if (abstractMesh instanceof BABYLON.Mesh) {
  98979. var mesh = abstractMesh;
  98980. if (!mesh.doNotSerialize) {
  98981. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98982. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98983. }
  98984. }
  98985. }
  98986. }
  98987. // Particles Systems
  98988. serializationObject.particleSystems = [];
  98989. for (index = 0; index < scene.particleSystems.length; index++) {
  98990. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98991. }
  98992. // Shadows
  98993. serializationObject.shadowGenerators = [];
  98994. for (index = 0; index < scene.lights.length; index++) {
  98995. light = scene.lights[index];
  98996. var shadowGenerator = light.getShadowGenerator();
  98997. if (shadowGenerator) {
  98998. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98999. }
  99000. }
  99001. // Action Manager
  99002. if (scene.actionManager) {
  99003. serializationObject.actions = scene.actionManager.serialize("scene");
  99004. }
  99005. // Audio
  99006. serializationObject.sounds = [];
  99007. for (index = 0; index < scene.soundTracks.length; index++) {
  99008. var soundtrack = scene.soundTracks[index];
  99009. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  99010. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  99011. }
  99012. }
  99013. // Components
  99014. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  99015. var component = _c[_b];
  99016. component.serialize(serializationObject);
  99017. }
  99018. return serializationObject;
  99019. };
  99020. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  99021. if (withParents === void 0) { withParents = false; }
  99022. if (withChildren === void 0) { withChildren = false; }
  99023. var serializationObject = {};
  99024. SceneSerializer.ClearCache();
  99025. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  99026. if (withParents || withChildren) {
  99027. //deliberate for loop! not for each, appended should be processed as well.
  99028. for (var i = 0; i < toSerialize.length; ++i) {
  99029. if (withChildren) {
  99030. toSerialize[i].getDescendants().forEach(function (node) {
  99031. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  99032. toSerialize.push(node);
  99033. }
  99034. });
  99035. }
  99036. //make sure the array doesn't contain the object already
  99037. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  99038. toSerialize.push(toSerialize[i].parent);
  99039. }
  99040. }
  99041. }
  99042. toSerialize.forEach(function (mesh) {
  99043. finalizeSingleMesh(mesh, serializationObject);
  99044. });
  99045. return serializationObject;
  99046. };
  99047. return SceneSerializer;
  99048. }());
  99049. BABYLON.SceneSerializer = SceneSerializer;
  99050. })(BABYLON || (BABYLON = {}));
  99051. //# sourceMappingURL=babylon.sceneSerializer.js.map
  99052. var BABYLON;
  99053. (function (BABYLON) {
  99054. var ReflectionProbe = /** @class */ (function () {
  99055. function ReflectionProbe(name, size, scene, generateMipMaps) {
  99056. if (generateMipMaps === void 0) { generateMipMaps = true; }
  99057. var _this = this;
  99058. this.name = name;
  99059. this._viewMatrix = BABYLON.Matrix.Identity();
  99060. this._target = BABYLON.Vector3.Zero();
  99061. this._add = BABYLON.Vector3.Zero();
  99062. this._invertYAxis = false;
  99063. this.position = BABYLON.Vector3.Zero();
  99064. this._scene = scene;
  99065. this._scene.reflectionProbes.push(this);
  99066. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  99067. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  99068. switch (faceIndex) {
  99069. case 0:
  99070. _this._add.copyFromFloats(1, 0, 0);
  99071. break;
  99072. case 1:
  99073. _this._add.copyFromFloats(-1, 0, 0);
  99074. break;
  99075. case 2:
  99076. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  99077. break;
  99078. case 3:
  99079. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  99080. break;
  99081. case 4:
  99082. _this._add.copyFromFloats(0, 0, 1);
  99083. break;
  99084. case 5:
  99085. _this._add.copyFromFloats(0, 0, -1);
  99086. break;
  99087. }
  99088. if (_this._attachedMesh) {
  99089. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  99090. }
  99091. _this.position.addToRef(_this._add, _this._target);
  99092. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  99093. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  99094. scene._forcedViewPosition = _this.position;
  99095. });
  99096. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  99097. scene._forcedViewPosition = null;
  99098. scene.updateTransformMatrix(true);
  99099. });
  99100. if (scene.activeCamera) {
  99101. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  99102. }
  99103. }
  99104. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  99105. get: function () {
  99106. return this._renderTargetTexture.samples;
  99107. },
  99108. set: function (value) {
  99109. this._renderTargetTexture.samples = value;
  99110. },
  99111. enumerable: true,
  99112. configurable: true
  99113. });
  99114. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  99115. get: function () {
  99116. return this._renderTargetTexture.refreshRate;
  99117. },
  99118. set: function (value) {
  99119. this._renderTargetTexture.refreshRate = value;
  99120. },
  99121. enumerable: true,
  99122. configurable: true
  99123. });
  99124. ReflectionProbe.prototype.getScene = function () {
  99125. return this._scene;
  99126. };
  99127. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  99128. get: function () {
  99129. return this._renderTargetTexture;
  99130. },
  99131. enumerable: true,
  99132. configurable: true
  99133. });
  99134. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  99135. get: function () {
  99136. return this._renderTargetTexture.renderList;
  99137. },
  99138. enumerable: true,
  99139. configurable: true
  99140. });
  99141. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  99142. this._attachedMesh = mesh;
  99143. };
  99144. /**
  99145. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  99146. *
  99147. * @param renderingGroupId The rendering group id corresponding to its index
  99148. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  99149. */
  99150. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  99151. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  99152. };
  99153. ReflectionProbe.prototype.dispose = function () {
  99154. var index = this._scene.reflectionProbes.indexOf(this);
  99155. if (index !== -1) {
  99156. // Remove from the scene if found
  99157. this._scene.reflectionProbes.splice(index, 1);
  99158. }
  99159. if (this._renderTargetTexture) {
  99160. this._renderTargetTexture.dispose();
  99161. this._renderTargetTexture = null;
  99162. }
  99163. };
  99164. return ReflectionProbe;
  99165. }());
  99166. BABYLON.ReflectionProbe = ReflectionProbe;
  99167. })(BABYLON || (BABYLON = {}));
  99168. //# sourceMappingURL=babylon.reflectionProbe.js.map
  99169. var BABYLON;
  99170. (function (BABYLON) {
  99171. /**
  99172. * Defines the layer scene component responsible to manage any layers
  99173. * in a given scene.
  99174. */
  99175. var LayerSceneComponent = /** @class */ (function () {
  99176. /**
  99177. * Creates a new instance of the component for the given scene
  99178. * @param scene Defines the scene to register the component in
  99179. */
  99180. function LayerSceneComponent(scene) {
  99181. /**
  99182. * The component name helpfull to identify the component in the list of scene components.
  99183. */
  99184. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  99185. this.scene = scene;
  99186. this._engine = scene.getEngine();
  99187. scene.layers = new Array();
  99188. }
  99189. /**
  99190. * Registers the component in a given scene
  99191. */
  99192. LayerSceneComponent.prototype.register = function () {
  99193. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  99194. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  99195. };
  99196. /**
  99197. * Rebuilds the elements related to this component in case of
  99198. * context lost for instance.
  99199. */
  99200. LayerSceneComponent.prototype.rebuild = function () {
  99201. var layers = this.scene.layers;
  99202. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  99203. var layer = layers_1[_i];
  99204. layer._rebuild();
  99205. }
  99206. };
  99207. /**
  99208. * Disposes the component and the associated ressources.
  99209. */
  99210. LayerSceneComponent.prototype.dispose = function () {
  99211. var layers = this.scene.layers;
  99212. while (layers.length) {
  99213. layers[0].dispose();
  99214. }
  99215. };
  99216. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  99217. var layers = this.scene.layers;
  99218. if (layers.length) {
  99219. this._engine.setDepthBuffer(false);
  99220. var cameraLayerMask = camera.layerMask;
  99221. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  99222. var layer = layers_2[_i];
  99223. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  99224. layer.render();
  99225. }
  99226. }
  99227. this._engine.setDepthBuffer(true);
  99228. }
  99229. };
  99230. LayerSceneComponent.prototype._drawBackground = function (camera) {
  99231. this._draw(camera, true);
  99232. };
  99233. LayerSceneComponent.prototype._drawForeground = function (camera) {
  99234. this._draw(camera, false);
  99235. };
  99236. return LayerSceneComponent;
  99237. }());
  99238. BABYLON.LayerSceneComponent = LayerSceneComponent;
  99239. })(BABYLON || (BABYLON = {}));
  99240. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  99241. var BABYLON;
  99242. (function (BABYLON) {
  99243. var Layer = /** @class */ (function () {
  99244. function Layer(name, imgUrl, scene, isBackground, color) {
  99245. this.name = name;
  99246. this.scale = new BABYLON.Vector2(1, 1);
  99247. this.offset = new BABYLON.Vector2(0, 0);
  99248. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  99249. this.layerMask = 0x0FFFFFFF;
  99250. this._vertexBuffers = {};
  99251. // Events
  99252. /**
  99253. * An event triggered when the layer is disposed.
  99254. */
  99255. this.onDisposeObservable = new BABYLON.Observable();
  99256. /**
  99257. * An event triggered before rendering the scene
  99258. */
  99259. this.onBeforeRenderObservable = new BABYLON.Observable();
  99260. /**
  99261. * An event triggered after rendering the scene
  99262. */
  99263. this.onAfterRenderObservable = new BABYLON.Observable();
  99264. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  99265. this.isBackground = isBackground === undefined ? true : isBackground;
  99266. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  99267. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  99268. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  99269. if (!layerComponent) {
  99270. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  99271. this._scene._addComponent(layerComponent);
  99272. }
  99273. this._scene.layers.push(this);
  99274. var engine = this._scene.getEngine();
  99275. // VBO
  99276. var vertices = [];
  99277. vertices.push(1, 1);
  99278. vertices.push(-1, 1);
  99279. vertices.push(-1, -1);
  99280. vertices.push(1, -1);
  99281. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99282. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99283. this._createIndexBuffer();
  99284. // Effects
  99285. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  99286. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  99287. }
  99288. Object.defineProperty(Layer.prototype, "onDispose", {
  99289. set: function (callback) {
  99290. if (this._onDisposeObserver) {
  99291. this.onDisposeObservable.remove(this._onDisposeObserver);
  99292. }
  99293. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  99294. },
  99295. enumerable: true,
  99296. configurable: true
  99297. });
  99298. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  99299. set: function (callback) {
  99300. if (this._onBeforeRenderObserver) {
  99301. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  99302. }
  99303. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  99304. },
  99305. enumerable: true,
  99306. configurable: true
  99307. });
  99308. Object.defineProperty(Layer.prototype, "onAfterRender", {
  99309. set: function (callback) {
  99310. if (this._onAfterRenderObserver) {
  99311. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99312. }
  99313. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  99314. },
  99315. enumerable: true,
  99316. configurable: true
  99317. });
  99318. Layer.prototype._createIndexBuffer = function () {
  99319. var engine = this._scene.getEngine();
  99320. // Indices
  99321. var indices = [];
  99322. indices.push(0);
  99323. indices.push(1);
  99324. indices.push(2);
  99325. indices.push(0);
  99326. indices.push(2);
  99327. indices.push(3);
  99328. this._indexBuffer = engine.createIndexBuffer(indices);
  99329. };
  99330. Layer.prototype._rebuild = function () {
  99331. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99332. if (vb) {
  99333. vb._rebuild();
  99334. }
  99335. this._createIndexBuffer();
  99336. };
  99337. Layer.prototype.render = function () {
  99338. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  99339. // Check
  99340. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  99341. return;
  99342. var engine = this._scene.getEngine();
  99343. this.onBeforeRenderObservable.notifyObservers(this);
  99344. // Render
  99345. engine.enableEffect(currentEffect);
  99346. engine.setState(false);
  99347. // Texture
  99348. currentEffect.setTexture("textureSampler", this.texture);
  99349. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  99350. // Color
  99351. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  99352. // Scale / offset
  99353. currentEffect.setVector2("offset", this.offset);
  99354. currentEffect.setVector2("scale", this.scale);
  99355. // VBOs
  99356. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99357. // Draw order
  99358. if (!this.alphaTest) {
  99359. engine.setAlphaMode(this.alphaBlendingMode);
  99360. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99361. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  99362. }
  99363. else {
  99364. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99365. }
  99366. this.onAfterRenderObservable.notifyObservers(this);
  99367. };
  99368. Layer.prototype.dispose = function () {
  99369. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99370. if (vertexBuffer) {
  99371. vertexBuffer.dispose();
  99372. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99373. }
  99374. if (this._indexBuffer) {
  99375. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99376. this._indexBuffer = null;
  99377. }
  99378. if (this.texture) {
  99379. this.texture.dispose();
  99380. this.texture = null;
  99381. }
  99382. // Remove from scene
  99383. var index = this._scene.layers.indexOf(this);
  99384. this._scene.layers.splice(index, 1);
  99385. // Callback
  99386. this.onDisposeObservable.notifyObservers(this);
  99387. this.onDisposeObservable.clear();
  99388. this.onAfterRenderObservable.clear();
  99389. this.onBeforeRenderObservable.clear();
  99390. };
  99391. return Layer;
  99392. }());
  99393. BABYLON.Layer = Layer;
  99394. })(BABYLON || (BABYLON = {}));
  99395. //# sourceMappingURL=babylon.layer.js.map
  99396. var BABYLON;
  99397. (function (BABYLON) {
  99398. var TextureTools = /** @class */ (function () {
  99399. function TextureTools() {
  99400. }
  99401. /**
  99402. * Uses the GPU to create a copy texture rescaled at a given size
  99403. * @param texture Texture to copy from
  99404. * @param width Desired width
  99405. * @param height Desired height
  99406. * @return Generated texture
  99407. */
  99408. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99409. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99410. var scene = texture.getScene();
  99411. var engine = scene.getEngine();
  99412. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99413. rtt.wrapU = texture.wrapU;
  99414. rtt.wrapV = texture.wrapV;
  99415. rtt.uOffset = texture.uOffset;
  99416. rtt.vOffset = texture.vOffset;
  99417. rtt.uScale = texture.uScale;
  99418. rtt.vScale = texture.vScale;
  99419. rtt.uAng = texture.uAng;
  99420. rtt.vAng = texture.vAng;
  99421. rtt.wAng = texture.wAng;
  99422. rtt.coordinatesIndex = texture.coordinatesIndex;
  99423. rtt.level = texture.level;
  99424. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99425. rtt._texture.isReady = false;
  99426. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99427. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99428. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99429. passPostProcess.getEffect().executeWhenCompiled(function () {
  99430. passPostProcess.onApply = function (effect) {
  99431. effect.setTexture("textureSampler", texture);
  99432. };
  99433. var internalTexture = rtt.getInternalTexture();
  99434. if (internalTexture) {
  99435. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99436. engine.unBindFramebuffer(internalTexture);
  99437. rtt.disposeFramebufferObjects();
  99438. passPostProcess.dispose();
  99439. internalTexture.isReady = true;
  99440. }
  99441. });
  99442. return rtt;
  99443. };
  99444. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99445. if (!scene._environmentBRDFTexture) {
  99446. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99447. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99448. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99449. scene._environmentBRDFTexture = texture;
  99450. }
  99451. return scene._environmentBRDFTexture;
  99452. };
  99453. 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=";
  99454. return TextureTools;
  99455. }());
  99456. BABYLON.TextureTools = TextureTools;
  99457. })(BABYLON || (BABYLON = {}));
  99458. //# sourceMappingURL=babylon.textureTools.js.map
  99459. var BABYLON;
  99460. (function (BABYLON) {
  99461. var FramingBehavior = /** @class */ (function () {
  99462. function FramingBehavior() {
  99463. this._mode = FramingBehavior.FitFrustumSidesMode;
  99464. this._radiusScale = 1.0;
  99465. this._positionScale = 0.5;
  99466. this._defaultElevation = 0.3;
  99467. this._elevationReturnTime = 1500;
  99468. this._elevationReturnWaitTime = 1000;
  99469. this._zoomStopsAnimation = false;
  99470. this._framingTime = 1500;
  99471. this._isPointerDown = false;
  99472. this._lastInteractionTime = -Infinity;
  99473. // Framing control
  99474. this._animatables = new Array();
  99475. this._betaIsAnimating = false;
  99476. }
  99477. Object.defineProperty(FramingBehavior.prototype, "name", {
  99478. get: function () {
  99479. return "Framing";
  99480. },
  99481. enumerable: true,
  99482. configurable: true
  99483. });
  99484. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99485. /**
  99486. * Gets current mode used by the behavior.
  99487. */
  99488. get: function () {
  99489. return this._mode;
  99490. },
  99491. /**
  99492. * Sets the current mode used by the behavior
  99493. */
  99494. set: function (mode) {
  99495. this._mode = mode;
  99496. },
  99497. enumerable: true,
  99498. configurable: true
  99499. });
  99500. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99501. /**
  99502. * Gets the scale applied to the radius
  99503. */
  99504. get: function () {
  99505. return this._radiusScale;
  99506. },
  99507. /**
  99508. * Sets the scale applied to the radius (1 by default)
  99509. */
  99510. set: function (radius) {
  99511. this._radiusScale = radius;
  99512. },
  99513. enumerable: true,
  99514. configurable: true
  99515. });
  99516. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99517. /**
  99518. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99519. */
  99520. get: function () {
  99521. return this._positionScale;
  99522. },
  99523. /**
  99524. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99525. */
  99526. set: function (scale) {
  99527. this._positionScale = scale;
  99528. },
  99529. enumerable: true,
  99530. configurable: true
  99531. });
  99532. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99533. /**
  99534. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99535. * behaviour is triggered, in radians.
  99536. */
  99537. get: function () {
  99538. return this._defaultElevation;
  99539. },
  99540. /**
  99541. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99542. * behaviour is triggered, in radians.
  99543. */
  99544. set: function (elevation) {
  99545. this._defaultElevation = elevation;
  99546. },
  99547. enumerable: true,
  99548. configurable: true
  99549. });
  99550. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99551. /**
  99552. * Gets the time (in milliseconds) taken to return to the default beta position.
  99553. * Negative value indicates camera should not return to default.
  99554. */
  99555. get: function () {
  99556. return this._elevationReturnTime;
  99557. },
  99558. /**
  99559. * Sets the time (in milliseconds) taken to return to the default beta position.
  99560. * Negative value indicates camera should not return to default.
  99561. */
  99562. set: function (speed) {
  99563. this._elevationReturnTime = speed;
  99564. },
  99565. enumerable: true,
  99566. configurable: true
  99567. });
  99568. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99569. /**
  99570. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99571. */
  99572. get: function () {
  99573. return this._elevationReturnWaitTime;
  99574. },
  99575. /**
  99576. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99577. */
  99578. set: function (time) {
  99579. this._elevationReturnWaitTime = time;
  99580. },
  99581. enumerable: true,
  99582. configurable: true
  99583. });
  99584. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99585. /**
  99586. * Gets the flag that indicates if user zooming should stop animation.
  99587. */
  99588. get: function () {
  99589. return this._zoomStopsAnimation;
  99590. },
  99591. /**
  99592. * Sets the flag that indicates if user zooming should stop animation.
  99593. */
  99594. set: function (flag) {
  99595. this._zoomStopsAnimation = flag;
  99596. },
  99597. enumerable: true,
  99598. configurable: true
  99599. });
  99600. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99601. /**
  99602. * Gets the transition time when framing the mesh, in milliseconds
  99603. */
  99604. get: function () {
  99605. return this._framingTime;
  99606. },
  99607. /**
  99608. * Sets the transition time when framing the mesh, in milliseconds
  99609. */
  99610. set: function (time) {
  99611. this._framingTime = time;
  99612. },
  99613. enumerable: true,
  99614. configurable: true
  99615. });
  99616. FramingBehavior.prototype.init = function () {
  99617. // Do notihng
  99618. };
  99619. FramingBehavior.prototype.attach = function (camera) {
  99620. var _this = this;
  99621. this._attachedCamera = camera;
  99622. var scene = this._attachedCamera.getScene();
  99623. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99624. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99625. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99626. _this._isPointerDown = true;
  99627. return;
  99628. }
  99629. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99630. _this._isPointerDown = false;
  99631. }
  99632. });
  99633. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99634. if (mesh) {
  99635. _this.zoomOnMesh(mesh);
  99636. }
  99637. });
  99638. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99639. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99640. _this._applyUserInteraction();
  99641. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99642. // back to the default position after a given timeout
  99643. _this._maintainCameraAboveGround();
  99644. });
  99645. };
  99646. FramingBehavior.prototype.detach = function () {
  99647. if (!this._attachedCamera) {
  99648. return;
  99649. }
  99650. var scene = this._attachedCamera.getScene();
  99651. if (this._onPrePointerObservableObserver) {
  99652. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99653. }
  99654. if (this._onAfterCheckInputsObserver) {
  99655. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99656. }
  99657. if (this._onMeshTargetChangedObserver) {
  99658. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99659. }
  99660. this._attachedCamera = null;
  99661. };
  99662. /**
  99663. * Targets the given mesh and updates zoom level accordingly.
  99664. * @param mesh The mesh to target.
  99665. * @param radius Optional. If a cached radius position already exists, overrides default.
  99666. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99667. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99668. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99669. */
  99670. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99671. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99672. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99673. mesh.computeWorldMatrix(true);
  99674. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99675. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99676. };
  99677. /**
  99678. * Targets the given mesh with its children and updates zoom level accordingly.
  99679. * @param mesh The mesh to target.
  99680. * @param radius Optional. If a cached radius position already exists, overrides default.
  99681. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99682. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99683. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99684. */
  99685. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99686. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99687. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99688. mesh.computeWorldMatrix(true);
  99689. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99690. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99691. };
  99692. /**
  99693. * Targets the given meshes with their children and updates zoom level accordingly.
  99694. * @param meshes The mesh to target.
  99695. * @param radius Optional. If a cached radius position already exists, overrides default.
  99696. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99697. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99698. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99699. */
  99700. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99701. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99702. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99703. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99704. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99705. for (var i = 0; i < meshes.length; i++) {
  99706. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99707. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99708. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99709. }
  99710. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99711. };
  99712. /**
  99713. * Targets the given mesh and updates zoom level accordingly.
  99714. * @param mesh The mesh to target.
  99715. * @param radius Optional. If a cached radius position already exists, overrides default.
  99716. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99717. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99718. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99719. */
  99720. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99721. var _this = this;
  99722. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99723. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99724. var zoomTarget;
  99725. if (!this._attachedCamera) {
  99726. return;
  99727. }
  99728. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99729. var bottom = minimumWorld.y;
  99730. var top = maximumWorld.y;
  99731. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99732. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99733. if (focusOnOriginXZ) {
  99734. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99735. }
  99736. else {
  99737. var centerWorld = minimumWorld.add(radiusWorld);
  99738. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99739. }
  99740. if (!this._vectorTransition) {
  99741. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99742. }
  99743. this._betaIsAnimating = true;
  99744. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99745. if (animatable) {
  99746. this._animatables.push(animatable);
  99747. }
  99748. // sets the radius and lower radius bounds
  99749. // Small delta ensures camera is not always at lower zoom limit.
  99750. var radius = 0;
  99751. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99752. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99753. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99754. radius = position;
  99755. }
  99756. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99757. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99758. if (this._attachedCamera.lowerRadiusLimit === null) {
  99759. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99760. }
  99761. }
  99762. // Set sensibilities
  99763. var extend = maximumWorld.subtract(minimumWorld).length();
  99764. this._attachedCamera.panningSensibility = 5000 / extend;
  99765. this._attachedCamera.wheelPrecision = 100 / radius;
  99766. // transition to new radius
  99767. if (!this._radiusTransition) {
  99768. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99769. }
  99770. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99771. _this.stopAllAnimations();
  99772. if (onAnimationEnd) {
  99773. onAnimationEnd();
  99774. }
  99775. if (_this._attachedCamera) {
  99776. _this._attachedCamera.storeState();
  99777. }
  99778. });
  99779. if (animatable) {
  99780. this._animatables.push(animatable);
  99781. }
  99782. };
  99783. /**
  99784. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99785. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99786. * frustum width.
  99787. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99788. * to fully enclose the mesh in the viewing frustum.
  99789. */
  99790. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99791. var size = maximumWorld.subtract(minimumWorld);
  99792. var boxVectorGlobalDiagonal = size.length();
  99793. var frustumSlope = this._getFrustumSlope();
  99794. // Formula for setting distance
  99795. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99796. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99797. // Horizon distance
  99798. var radius = radiusWithoutFraming * this._radiusScale;
  99799. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99800. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99801. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99802. var camera = this._attachedCamera;
  99803. if (!camera) {
  99804. return 0;
  99805. }
  99806. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99807. // Don't exceed the requested limit
  99808. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99809. }
  99810. // Don't exceed the upper radius limit
  99811. if (camera.upperRadiusLimit) {
  99812. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99813. }
  99814. return distance;
  99815. };
  99816. /**
  99817. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99818. * is automatically returned to its default position (expected to be above ground plane).
  99819. */
  99820. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99821. var _this = this;
  99822. if (this._elevationReturnTime < 0) {
  99823. return;
  99824. }
  99825. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99826. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99827. var limitBeta = Math.PI * 0.5;
  99828. // Bring the camera back up if below the ground plane
  99829. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99830. this._betaIsAnimating = true;
  99831. //Transition to new position
  99832. this.stopAllAnimations();
  99833. if (!this._betaTransition) {
  99834. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99835. }
  99836. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99837. _this._clearAnimationLocks();
  99838. _this.stopAllAnimations();
  99839. });
  99840. if (animatabe) {
  99841. this._animatables.push(animatabe);
  99842. }
  99843. }
  99844. };
  99845. /**
  99846. * Returns the frustum slope based on the canvas ratio and camera FOV
  99847. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99848. */
  99849. FramingBehavior.prototype._getFrustumSlope = function () {
  99850. // Calculate the viewport ratio
  99851. // Aspect Ratio is Height/Width.
  99852. var camera = this._attachedCamera;
  99853. if (!camera) {
  99854. return BABYLON.Vector2.Zero();
  99855. }
  99856. var engine = camera.getScene().getEngine();
  99857. var aspectRatio = engine.getAspectRatio(camera);
  99858. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99859. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99860. var frustumSlopeY = Math.tan(camera.fov / 2);
  99861. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99862. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99863. // along the forward vector.
  99864. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99865. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99866. };
  99867. /**
  99868. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99869. */
  99870. FramingBehavior.prototype._clearAnimationLocks = function () {
  99871. this._betaIsAnimating = false;
  99872. };
  99873. /**
  99874. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99875. */
  99876. FramingBehavior.prototype._applyUserInteraction = function () {
  99877. if (this.isUserIsMoving) {
  99878. this._lastInteractionTime = BABYLON.Tools.Now;
  99879. this.stopAllAnimations();
  99880. this._clearAnimationLocks();
  99881. }
  99882. };
  99883. /**
  99884. * Stops and removes all animations that have been applied to the camera
  99885. */
  99886. FramingBehavior.prototype.stopAllAnimations = function () {
  99887. if (this._attachedCamera) {
  99888. this._attachedCamera.animations = [];
  99889. }
  99890. while (this._animatables.length) {
  99891. if (this._animatables[0]) {
  99892. this._animatables[0].onAnimationEnd = null;
  99893. this._animatables[0].stop();
  99894. }
  99895. this._animatables.shift();
  99896. }
  99897. };
  99898. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99899. /**
  99900. * Gets a value indicating if the user is moving the camera
  99901. */
  99902. get: function () {
  99903. if (!this._attachedCamera) {
  99904. return false;
  99905. }
  99906. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99907. this._attachedCamera.inertialBetaOffset !== 0 ||
  99908. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99909. this._attachedCamera.inertialPanningX !== 0 ||
  99910. this._attachedCamera.inertialPanningY !== 0 ||
  99911. this._isPointerDown;
  99912. },
  99913. enumerable: true,
  99914. configurable: true
  99915. });
  99916. /**
  99917. * The easing function used by animations
  99918. */
  99919. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99920. /**
  99921. * The easing mode used by animations
  99922. */
  99923. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99924. // Statics
  99925. /**
  99926. * The camera can move all the way towards the mesh.
  99927. */
  99928. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99929. /**
  99930. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99931. */
  99932. FramingBehavior.FitFrustumSidesMode = 1;
  99933. return FramingBehavior;
  99934. }());
  99935. BABYLON.FramingBehavior = FramingBehavior;
  99936. })(BABYLON || (BABYLON = {}));
  99937. //# sourceMappingURL=babylon.framingBehavior.js.map
  99938. var BABYLON;
  99939. (function (BABYLON) {
  99940. /**
  99941. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99942. */
  99943. var BouncingBehavior = /** @class */ (function () {
  99944. function BouncingBehavior() {
  99945. /**
  99946. * The duration of the animation, in milliseconds
  99947. */
  99948. this.transitionDuration = 450;
  99949. /**
  99950. * Length of the distance animated by the transition when lower radius is reached
  99951. */
  99952. this.lowerRadiusTransitionRange = 2;
  99953. /**
  99954. * Length of the distance animated by the transition when upper radius is reached
  99955. */
  99956. this.upperRadiusTransitionRange = -2;
  99957. this._autoTransitionRange = false;
  99958. // Animations
  99959. this._radiusIsAnimating = false;
  99960. this._radiusBounceTransition = null;
  99961. this._animatables = new Array();
  99962. }
  99963. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99964. get: function () {
  99965. return "Bouncing";
  99966. },
  99967. enumerable: true,
  99968. configurable: true
  99969. });
  99970. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99971. /**
  99972. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99973. */
  99974. get: function () {
  99975. return this._autoTransitionRange;
  99976. },
  99977. /**
  99978. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99979. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99980. */
  99981. set: function (value) {
  99982. var _this = this;
  99983. if (this._autoTransitionRange === value) {
  99984. return;
  99985. }
  99986. this._autoTransitionRange = value;
  99987. var camera = this._attachedCamera;
  99988. if (!camera) {
  99989. return;
  99990. }
  99991. if (value) {
  99992. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99993. if (!mesh) {
  99994. return;
  99995. }
  99996. mesh.computeWorldMatrix(true);
  99997. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99998. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99999. _this.upperRadiusTransitionRange = diagonal * 0.05;
  100000. });
  100001. }
  100002. else if (this._onMeshTargetChangedObserver) {
  100003. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100004. }
  100005. },
  100006. enumerable: true,
  100007. configurable: true
  100008. });
  100009. BouncingBehavior.prototype.init = function () {
  100010. // Do notihng
  100011. };
  100012. BouncingBehavior.prototype.attach = function (camera) {
  100013. var _this = this;
  100014. this._attachedCamera = camera;
  100015. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100016. if (!_this._attachedCamera) {
  100017. return;
  100018. }
  100019. // Add the bounce animation to the lower radius limit
  100020. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  100021. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  100022. }
  100023. // Add the bounce animation to the upper radius limit
  100024. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  100025. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  100026. }
  100027. });
  100028. };
  100029. BouncingBehavior.prototype.detach = function () {
  100030. if (!this._attachedCamera) {
  100031. return;
  100032. }
  100033. if (this._onAfterCheckInputsObserver) {
  100034. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100035. }
  100036. if (this._onMeshTargetChangedObserver) {
  100037. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  100038. }
  100039. this._attachedCamera = null;
  100040. };
  100041. /**
  100042. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  100043. * @param radiusLimit The limit to check against.
  100044. * @return Bool to indicate if at limit.
  100045. */
  100046. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  100047. if (!this._attachedCamera) {
  100048. return false;
  100049. }
  100050. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  100051. return true;
  100052. }
  100053. return false;
  100054. };
  100055. /**
  100056. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  100057. * @param radiusDelta The delta by which to animate to. Can be negative.
  100058. */
  100059. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  100060. var _this = this;
  100061. if (!this._attachedCamera) {
  100062. return;
  100063. }
  100064. if (!this._radiusBounceTransition) {
  100065. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  100066. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  100067. }
  100068. // Prevent zoom until bounce has completed
  100069. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  100070. this._attachedCamera.wheelPrecision = Infinity;
  100071. this._attachedCamera.inertialRadiusOffset = 0;
  100072. // Animate to the radius limit
  100073. this.stopAllAnimations();
  100074. this._radiusIsAnimating = true;
  100075. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  100076. if (animatable) {
  100077. this._animatables.push(animatable);
  100078. }
  100079. };
  100080. /**
  100081. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  100082. */
  100083. BouncingBehavior.prototype._clearAnimationLocks = function () {
  100084. this._radiusIsAnimating = false;
  100085. if (this._attachedCamera) {
  100086. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  100087. }
  100088. };
  100089. /**
  100090. * Stops and removes all animations that have been applied to the camera
  100091. */
  100092. BouncingBehavior.prototype.stopAllAnimations = function () {
  100093. if (this._attachedCamera) {
  100094. this._attachedCamera.animations = [];
  100095. }
  100096. while (this._animatables.length) {
  100097. this._animatables[0].onAnimationEnd = null;
  100098. this._animatables[0].stop();
  100099. this._animatables.shift();
  100100. }
  100101. };
  100102. /**
  100103. * The easing function used by animations
  100104. */
  100105. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  100106. /**
  100107. * The easing mode used by animations
  100108. */
  100109. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  100110. return BouncingBehavior;
  100111. }());
  100112. BABYLON.BouncingBehavior = BouncingBehavior;
  100113. })(BABYLON || (BABYLON = {}));
  100114. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  100115. var BABYLON;
  100116. (function (BABYLON) {
  100117. var AutoRotationBehavior = /** @class */ (function () {
  100118. function AutoRotationBehavior() {
  100119. this._zoomStopsAnimation = false;
  100120. this._idleRotationSpeed = 0.05;
  100121. this._idleRotationWaitTime = 2000;
  100122. this._idleRotationSpinupTime = 2000;
  100123. this._isPointerDown = false;
  100124. this._lastFrameTime = null;
  100125. this._lastInteractionTime = -Infinity;
  100126. this._cameraRotationSpeed = 0;
  100127. this._lastFrameRadius = 0;
  100128. }
  100129. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  100130. get: function () {
  100131. return "AutoRotation";
  100132. },
  100133. enumerable: true,
  100134. configurable: true
  100135. });
  100136. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  100137. /**
  100138. * Gets the flag that indicates if user zooming should stop animation.
  100139. */
  100140. get: function () {
  100141. return this._zoomStopsAnimation;
  100142. },
  100143. /**
  100144. * Sets the flag that indicates if user zooming should stop animation.
  100145. */
  100146. set: function (flag) {
  100147. this._zoomStopsAnimation = flag;
  100148. },
  100149. enumerable: true,
  100150. configurable: true
  100151. });
  100152. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  100153. /**
  100154. * Gets the default speed at which the camera rotates around the model.
  100155. */
  100156. get: function () {
  100157. return this._idleRotationSpeed;
  100158. },
  100159. /**
  100160. * Sets the default speed at which the camera rotates around the model.
  100161. */
  100162. set: function (speed) {
  100163. this._idleRotationSpeed = speed;
  100164. },
  100165. enumerable: true,
  100166. configurable: true
  100167. });
  100168. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  100169. /**
  100170. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  100171. */
  100172. get: function () {
  100173. return this._idleRotationWaitTime;
  100174. },
  100175. /**
  100176. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  100177. */
  100178. set: function (time) {
  100179. this._idleRotationWaitTime = time;
  100180. },
  100181. enumerable: true,
  100182. configurable: true
  100183. });
  100184. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  100185. /**
  100186. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100187. */
  100188. get: function () {
  100189. return this._idleRotationSpinupTime;
  100190. },
  100191. /**
  100192. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  100193. */
  100194. set: function (time) {
  100195. this._idleRotationSpinupTime = time;
  100196. },
  100197. enumerable: true,
  100198. configurable: true
  100199. });
  100200. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  100201. /**
  100202. * Gets a value indicating if the camera is currently rotating because of this behavior
  100203. */
  100204. get: function () {
  100205. return Math.abs(this._cameraRotationSpeed) > 0;
  100206. },
  100207. enumerable: true,
  100208. configurable: true
  100209. });
  100210. AutoRotationBehavior.prototype.init = function () {
  100211. // Do notihng
  100212. };
  100213. AutoRotationBehavior.prototype.attach = function (camera) {
  100214. var _this = this;
  100215. this._attachedCamera = camera;
  100216. var scene = this._attachedCamera.getScene();
  100217. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  100218. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  100219. _this._isPointerDown = true;
  100220. return;
  100221. }
  100222. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  100223. _this._isPointerDown = false;
  100224. }
  100225. });
  100226. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  100227. var now = BABYLON.Tools.Now;
  100228. var dt = 0;
  100229. if (_this._lastFrameTime != null) {
  100230. dt = now - _this._lastFrameTime;
  100231. }
  100232. _this._lastFrameTime = now;
  100233. // Stop the animation if there is user interaction and the animation should stop for this interaction
  100234. _this._applyUserInteraction();
  100235. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  100236. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  100237. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  100238. // Step camera rotation by rotation speed
  100239. if (_this._attachedCamera) {
  100240. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  100241. }
  100242. });
  100243. };
  100244. AutoRotationBehavior.prototype.detach = function () {
  100245. if (!this._attachedCamera) {
  100246. return;
  100247. }
  100248. var scene = this._attachedCamera.getScene();
  100249. if (this._onPrePointerObservableObserver) {
  100250. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  100251. }
  100252. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  100253. this._attachedCamera = null;
  100254. };
  100255. /**
  100256. * Returns true if user is scrolling.
  100257. * @return true if user is scrolling.
  100258. */
  100259. AutoRotationBehavior.prototype._userIsZooming = function () {
  100260. if (!this._attachedCamera) {
  100261. return false;
  100262. }
  100263. return this._attachedCamera.inertialRadiusOffset !== 0;
  100264. };
  100265. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  100266. if (!this._attachedCamera) {
  100267. return false;
  100268. }
  100269. var zoomHasHitLimit = false;
  100270. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  100271. zoomHasHitLimit = true;
  100272. }
  100273. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  100274. this._lastFrameRadius = this._attachedCamera.radius;
  100275. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  100276. };
  100277. /**
  100278. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  100279. */
  100280. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  100281. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  100282. this._lastInteractionTime = BABYLON.Tools.Now;
  100283. }
  100284. };
  100285. // Tools
  100286. AutoRotationBehavior.prototype._userIsMoving = function () {
  100287. if (!this._attachedCamera) {
  100288. return false;
  100289. }
  100290. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  100291. this._attachedCamera.inertialBetaOffset !== 0 ||
  100292. this._attachedCamera.inertialRadiusOffset !== 0 ||
  100293. this._attachedCamera.inertialPanningX !== 0 ||
  100294. this._attachedCamera.inertialPanningY !== 0 ||
  100295. this._isPointerDown;
  100296. };
  100297. return AutoRotationBehavior;
  100298. }());
  100299. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  100300. })(BABYLON || (BABYLON = {}));
  100301. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  100302. var BABYLON;
  100303. (function (BABYLON) {
  100304. var NullEngineOptions = /** @class */ (function () {
  100305. function NullEngineOptions() {
  100306. this.renderWidth = 512;
  100307. this.renderHeight = 256;
  100308. this.textureSize = 512;
  100309. this.deterministicLockstep = false;
  100310. this.lockstepMaxSteps = 4;
  100311. }
  100312. return NullEngineOptions;
  100313. }());
  100314. BABYLON.NullEngineOptions = NullEngineOptions;
  100315. /**
  100316. * The null engine class provides support for headless version of babylon.js.
  100317. * This can be used in server side scenario or for testing purposes
  100318. */
  100319. var NullEngine = /** @class */ (function (_super) {
  100320. __extends(NullEngine, _super);
  100321. function NullEngine(options) {
  100322. if (options === void 0) { options = new NullEngineOptions(); }
  100323. var _this = _super.call(this, null) || this;
  100324. if (options.deterministicLockstep === undefined) {
  100325. options.deterministicLockstep = false;
  100326. }
  100327. if (options.lockstepMaxSteps === undefined) {
  100328. options.lockstepMaxSteps = 4;
  100329. }
  100330. _this._options = options;
  100331. // Init caps
  100332. // We consider we are on a webgl1 capable device
  100333. _this._caps = new BABYLON.EngineCapabilities();
  100334. _this._caps.maxTexturesImageUnits = 16;
  100335. _this._caps.maxVertexTextureImageUnits = 16;
  100336. _this._caps.maxTextureSize = 512;
  100337. _this._caps.maxCubemapTextureSize = 512;
  100338. _this._caps.maxRenderTextureSize = 512;
  100339. _this._caps.maxVertexAttribs = 16;
  100340. _this._caps.maxVaryingVectors = 16;
  100341. _this._caps.maxFragmentUniformVectors = 16;
  100342. _this._caps.maxVertexUniformVectors = 16;
  100343. // Extensions
  100344. _this._caps.standardDerivatives = false;
  100345. _this._caps.astc = null;
  100346. _this._caps.s3tc = null;
  100347. _this._caps.pvrtc = null;
  100348. _this._caps.etc1 = null;
  100349. _this._caps.etc2 = null;
  100350. _this._caps.textureAnisotropicFilterExtension = null;
  100351. _this._caps.maxAnisotropy = 0;
  100352. _this._caps.uintIndices = false;
  100353. _this._caps.fragmentDepthSupported = false;
  100354. _this._caps.highPrecisionShaderSupported = true;
  100355. _this._caps.colorBufferFloat = false;
  100356. _this._caps.textureFloat = false;
  100357. _this._caps.textureFloatLinearFiltering = false;
  100358. _this._caps.textureFloatRender = false;
  100359. _this._caps.textureHalfFloat = false;
  100360. _this._caps.textureHalfFloatLinearFiltering = false;
  100361. _this._caps.textureHalfFloatRender = false;
  100362. _this._caps.textureLOD = false;
  100363. _this._caps.drawBuffersExtension = false;
  100364. _this._caps.depthTextureExtension = false;
  100365. _this._caps.vertexArrayObject = false;
  100366. _this._caps.instancedArrays = false;
  100367. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  100368. // Wrappers
  100369. if (typeof URL === "undefined") {
  100370. URL = {
  100371. createObjectURL: function () { },
  100372. revokeObjectURL: function () { }
  100373. };
  100374. }
  100375. if (typeof Blob === "undefined") {
  100376. Blob = function () { };
  100377. }
  100378. return _this;
  100379. }
  100380. NullEngine.prototype.isDeterministicLockStep = function () {
  100381. return this._options.deterministicLockstep;
  100382. };
  100383. NullEngine.prototype.getLockstepMaxSteps = function () {
  100384. return this._options.lockstepMaxSteps;
  100385. };
  100386. NullEngine.prototype.getHardwareScalingLevel = function () {
  100387. return 1.0;
  100388. };
  100389. NullEngine.prototype.createVertexBuffer = function (vertices) {
  100390. return {
  100391. capacity: 0,
  100392. references: 1,
  100393. is32Bits: false
  100394. };
  100395. };
  100396. NullEngine.prototype.createIndexBuffer = function (indices) {
  100397. return {
  100398. capacity: 0,
  100399. references: 1,
  100400. is32Bits: false
  100401. };
  100402. };
  100403. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  100404. if (stencil === void 0) { stencil = false; }
  100405. };
  100406. NullEngine.prototype.getRenderWidth = function (useScreen) {
  100407. if (useScreen === void 0) { useScreen = false; }
  100408. if (!useScreen && this._currentRenderTarget) {
  100409. return this._currentRenderTarget.width;
  100410. }
  100411. return this._options.renderWidth;
  100412. };
  100413. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100414. if (useScreen === void 0) { useScreen = false; }
  100415. if (!useScreen && this._currentRenderTarget) {
  100416. return this._currentRenderTarget.height;
  100417. }
  100418. return this._options.renderHeight;
  100419. };
  100420. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100421. this._cachedViewport = viewport;
  100422. };
  100423. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100424. return {
  100425. transformFeedback: null,
  100426. __SPECTOR_rebuildProgram: null
  100427. };
  100428. };
  100429. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100430. return [];
  100431. };
  100432. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100433. return [];
  100434. };
  100435. NullEngine.prototype.bindSamplers = function (effect) {
  100436. this._currentEffect = null;
  100437. };
  100438. NullEngine.prototype.enableEffect = function (effect) {
  100439. this._currentEffect = effect;
  100440. if (effect.onBind) {
  100441. effect.onBind(effect);
  100442. }
  100443. effect.onBindObservable.notifyObservers(effect);
  100444. };
  100445. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100446. if (zOffset === void 0) { zOffset = 0; }
  100447. if (reverseSide === void 0) { reverseSide = false; }
  100448. };
  100449. NullEngine.prototype.setIntArray = function (uniform, array) {
  100450. };
  100451. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100452. };
  100453. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100454. };
  100455. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100456. };
  100457. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100458. };
  100459. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100460. };
  100461. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100462. };
  100463. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100464. };
  100465. NullEngine.prototype.setArray = function (uniform, array) {
  100466. };
  100467. NullEngine.prototype.setArray2 = function (uniform, array) {
  100468. };
  100469. NullEngine.prototype.setArray3 = function (uniform, array) {
  100470. };
  100471. NullEngine.prototype.setArray4 = function (uniform, array) {
  100472. };
  100473. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100474. };
  100475. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100476. };
  100477. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100478. };
  100479. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100480. };
  100481. NullEngine.prototype.setFloat = function (uniform, value) {
  100482. };
  100483. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100484. };
  100485. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100486. };
  100487. NullEngine.prototype.setBool = function (uniform, bool) {
  100488. };
  100489. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100490. };
  100491. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100492. };
  100493. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100494. };
  100495. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100496. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100497. if (this._alphaMode === mode) {
  100498. return;
  100499. }
  100500. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100501. if (!noDepthWriteChange) {
  100502. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100503. }
  100504. this._alphaMode = mode;
  100505. };
  100506. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100507. };
  100508. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100509. if (this.preventCacheWipeBetweenFrames) {
  100510. return;
  100511. }
  100512. this.resetTextureCache();
  100513. this._currentEffect = null;
  100514. if (bruteForce) {
  100515. this._currentProgram = null;
  100516. this._stencilState.reset();
  100517. this._depthCullingState.reset();
  100518. this._alphaState.reset();
  100519. }
  100520. this._cachedVertexBuffers = null;
  100521. this._cachedIndexBuffer = null;
  100522. this._cachedEffectForVertexBuffers = null;
  100523. };
  100524. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100525. };
  100526. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100527. };
  100528. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100529. };
  100530. NullEngine.prototype._createTexture = function () {
  100531. return {};
  100532. };
  100533. NullEngine.prototype._releaseTexture = function (texture) {
  100534. };
  100535. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100536. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100537. if (onLoad === void 0) { onLoad = null; }
  100538. if (onError === void 0) { onError = null; }
  100539. if (buffer === void 0) { buffer = null; }
  100540. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100541. var url = String(urlArg);
  100542. texture.url = url;
  100543. texture.generateMipMaps = !noMipmap;
  100544. texture.samplingMode = samplingMode;
  100545. texture.invertY = invertY;
  100546. texture.baseWidth = this._options.textureSize;
  100547. texture.baseHeight = this._options.textureSize;
  100548. texture.width = this._options.textureSize;
  100549. texture.height = this._options.textureSize;
  100550. if (format) {
  100551. texture.format = format;
  100552. }
  100553. texture.isReady = true;
  100554. if (onLoad) {
  100555. onLoad();
  100556. }
  100557. this._internalTexturesCache.push(texture);
  100558. return texture;
  100559. };
  100560. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100561. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100562. if (options !== undefined && typeof options === "object") {
  100563. fullOptions.generateMipMaps = options.generateMipMaps;
  100564. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100565. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100566. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100567. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100568. }
  100569. else {
  100570. fullOptions.generateMipMaps = options;
  100571. fullOptions.generateDepthBuffer = true;
  100572. fullOptions.generateStencilBuffer = false;
  100573. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100574. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100575. }
  100576. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100577. var width = size.width || size;
  100578. var height = size.height || size;
  100579. texture._depthStencilBuffer = {};
  100580. texture._framebuffer = {};
  100581. texture.baseWidth = width;
  100582. texture.baseHeight = height;
  100583. texture.width = width;
  100584. texture.height = height;
  100585. texture.isReady = true;
  100586. texture.samples = 1;
  100587. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100588. texture.samplingMode = fullOptions.samplingMode;
  100589. texture.type = fullOptions.type;
  100590. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100591. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100592. this._internalTexturesCache.push(texture);
  100593. return texture;
  100594. };
  100595. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100596. texture.samplingMode = samplingMode;
  100597. };
  100598. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100599. if (this._currentRenderTarget) {
  100600. this.unBindFramebuffer(this._currentRenderTarget);
  100601. }
  100602. this._currentRenderTarget = texture;
  100603. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100604. if (this._cachedViewport && !forceFullscreenViewport) {
  100605. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100606. }
  100607. };
  100608. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100609. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100610. this._currentRenderTarget = null;
  100611. if (onBeforeUnbind) {
  100612. if (texture._MSAAFramebuffer) {
  100613. this._currentFramebuffer = texture._framebuffer;
  100614. }
  100615. onBeforeUnbind();
  100616. }
  100617. this._currentFramebuffer = null;
  100618. };
  100619. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100620. var vbo = {
  100621. capacity: 1,
  100622. references: 1,
  100623. is32Bits: false
  100624. };
  100625. return vbo;
  100626. };
  100627. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100628. if (premulAlpha === void 0) { premulAlpha = false; }
  100629. };
  100630. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100631. if (offset === void 0) { offset = 0; }
  100632. };
  100633. /**
  100634. * Updates a dynamic vertex buffer.
  100635. * @param vertexBuffer the vertex buffer to update
  100636. * @param data the data used to update the vertex buffer
  100637. * @param byteOffset the byte offset of the data (optional)
  100638. * @param byteLength the byte length of the data (optional)
  100639. */
  100640. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100641. };
  100642. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100643. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100644. this._boundTexturesCache[this._activeChannel] = texture;
  100645. return true;
  100646. }
  100647. return false;
  100648. };
  100649. NullEngine.prototype._bindTexture = function (channel, texture) {
  100650. if (channel < 0) {
  100651. return;
  100652. }
  100653. this._bindTextureDirectly(0, texture);
  100654. };
  100655. NullEngine.prototype._releaseBuffer = function (buffer) {
  100656. buffer.references--;
  100657. if (buffer.references === 0) {
  100658. return true;
  100659. }
  100660. return false;
  100661. };
  100662. NullEngine.prototype.releaseEffects = function () {
  100663. };
  100664. NullEngine.prototype.displayLoadingUI = function () {
  100665. };
  100666. NullEngine.prototype.hideLoadingUI = function () {
  100667. };
  100668. return NullEngine;
  100669. }(BABYLON.Engine));
  100670. BABYLON.NullEngine = NullEngine;
  100671. })(BABYLON || (BABYLON = {}));
  100672. //# sourceMappingURL=babylon.nullEngine.js.map
  100673. var BABYLON;
  100674. (function (BABYLON) {
  100675. /**
  100676. * This class can be used to get instrumentation data from a Babylon engine
  100677. */
  100678. var EngineInstrumentation = /** @class */ (function () {
  100679. function EngineInstrumentation(engine) {
  100680. this.engine = engine;
  100681. this._captureGPUFrameTime = false;
  100682. this._gpuFrameTime = new BABYLON.PerfCounter();
  100683. this._captureShaderCompilationTime = false;
  100684. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100685. // Observers
  100686. this._onBeginFrameObserver = null;
  100687. this._onEndFrameObserver = null;
  100688. this._onBeforeShaderCompilationObserver = null;
  100689. this._onAfterShaderCompilationObserver = null;
  100690. }
  100691. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100692. // Properties
  100693. /**
  100694. * Gets the perf counter used for GPU frame time
  100695. */
  100696. get: function () {
  100697. return this._gpuFrameTime;
  100698. },
  100699. enumerable: true,
  100700. configurable: true
  100701. });
  100702. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100703. /**
  100704. * Gets the GPU frame time capture status
  100705. */
  100706. get: function () {
  100707. return this._captureGPUFrameTime;
  100708. },
  100709. /**
  100710. * Enable or disable the GPU frame time capture
  100711. */
  100712. set: function (value) {
  100713. var _this = this;
  100714. if (value === this._captureGPUFrameTime) {
  100715. return;
  100716. }
  100717. this._captureGPUFrameTime = value;
  100718. if (value) {
  100719. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100720. if (!_this._gpuFrameTimeToken) {
  100721. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100722. }
  100723. });
  100724. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100725. if (!_this._gpuFrameTimeToken) {
  100726. return;
  100727. }
  100728. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100729. if (time > -1) {
  100730. _this._gpuFrameTimeToken = null;
  100731. _this._gpuFrameTime.fetchNewFrame();
  100732. _this._gpuFrameTime.addCount(time, true);
  100733. }
  100734. });
  100735. }
  100736. else {
  100737. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100738. this._onBeginFrameObserver = null;
  100739. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100740. this._onEndFrameObserver = null;
  100741. }
  100742. },
  100743. enumerable: true,
  100744. configurable: true
  100745. });
  100746. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100747. /**
  100748. * Gets the perf counter used for shader compilation time
  100749. */
  100750. get: function () {
  100751. return this._shaderCompilationTime;
  100752. },
  100753. enumerable: true,
  100754. configurable: true
  100755. });
  100756. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100757. /**
  100758. * Gets the shader compilation time capture status
  100759. */
  100760. get: function () {
  100761. return this._captureShaderCompilationTime;
  100762. },
  100763. /**
  100764. * Enable or disable the shader compilation time capture
  100765. */
  100766. set: function (value) {
  100767. var _this = this;
  100768. if (value === this._captureShaderCompilationTime) {
  100769. return;
  100770. }
  100771. this._captureShaderCompilationTime = value;
  100772. if (value) {
  100773. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100774. _this._shaderCompilationTime.fetchNewFrame();
  100775. _this._shaderCompilationTime.beginMonitoring();
  100776. });
  100777. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100778. _this._shaderCompilationTime.endMonitoring();
  100779. });
  100780. }
  100781. else {
  100782. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100783. this._onBeforeShaderCompilationObserver = null;
  100784. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100785. this._onAfterShaderCompilationObserver = null;
  100786. }
  100787. },
  100788. enumerable: true,
  100789. configurable: true
  100790. });
  100791. EngineInstrumentation.prototype.dispose = function () {
  100792. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100793. this._onBeginFrameObserver = null;
  100794. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100795. this._onEndFrameObserver = null;
  100796. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100797. this._onBeforeShaderCompilationObserver = null;
  100798. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100799. this._onAfterShaderCompilationObserver = null;
  100800. this.engine = null;
  100801. };
  100802. return EngineInstrumentation;
  100803. }());
  100804. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100805. })(BABYLON || (BABYLON = {}));
  100806. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100807. var BABYLON;
  100808. (function (BABYLON) {
  100809. /**
  100810. * This class can be used to get instrumentation data from a Babylon engine
  100811. */
  100812. var SceneInstrumentation = /** @class */ (function () {
  100813. function SceneInstrumentation(scene) {
  100814. var _this = this;
  100815. this.scene = scene;
  100816. this._captureActiveMeshesEvaluationTime = false;
  100817. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100818. this._captureRenderTargetsRenderTime = false;
  100819. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100820. this._captureFrameTime = false;
  100821. this._frameTime = new BABYLON.PerfCounter();
  100822. this._captureRenderTime = false;
  100823. this._renderTime = new BABYLON.PerfCounter();
  100824. this._captureInterFrameTime = false;
  100825. this._interFrameTime = new BABYLON.PerfCounter();
  100826. this._captureParticlesRenderTime = false;
  100827. this._particlesRenderTime = new BABYLON.PerfCounter();
  100828. this._captureSpritesRenderTime = false;
  100829. this._spritesRenderTime = new BABYLON.PerfCounter();
  100830. this._capturePhysicsTime = false;
  100831. this._physicsTime = new BABYLON.PerfCounter();
  100832. this._captureAnimationsTime = false;
  100833. this._animationsTime = new BABYLON.PerfCounter();
  100834. this._captureCameraRenderTime = false;
  100835. this._cameraRenderTime = new BABYLON.PerfCounter();
  100836. // Observers
  100837. this._onBeforeActiveMeshesEvaluationObserver = null;
  100838. this._onAfterActiveMeshesEvaluationObserver = null;
  100839. this._onBeforeRenderTargetsRenderObserver = null;
  100840. this._onAfterRenderTargetsRenderObserver = null;
  100841. this._onAfterRenderObserver = null;
  100842. this._onBeforeDrawPhaseObserver = null;
  100843. this._onAfterDrawPhaseObserver = null;
  100844. this._onBeforeAnimationsObserver = null;
  100845. this._onBeforeParticlesRenderingObserver = null;
  100846. this._onAfterParticlesRenderingObserver = null;
  100847. this._onBeforeSpritesRenderingObserver = null;
  100848. this._onAfterSpritesRenderingObserver = null;
  100849. this._onBeforePhysicsObserver = null;
  100850. this._onAfterPhysicsObserver = null;
  100851. this._onAfterAnimationsObserver = null;
  100852. this._onBeforeCameraRenderObserver = null;
  100853. this._onAfterCameraRenderObserver = null;
  100854. // Before render
  100855. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100856. if (_this._captureActiveMeshesEvaluationTime) {
  100857. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100858. }
  100859. if (_this._captureRenderTargetsRenderTime) {
  100860. _this._renderTargetsRenderTime.fetchNewFrame();
  100861. }
  100862. if (_this._captureFrameTime) {
  100863. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100864. _this._frameTime.beginMonitoring();
  100865. }
  100866. if (_this._captureInterFrameTime) {
  100867. _this._interFrameTime.endMonitoring();
  100868. }
  100869. if (_this._captureParticlesRenderTime) {
  100870. _this._particlesRenderTime.fetchNewFrame();
  100871. }
  100872. if (_this._captureSpritesRenderTime) {
  100873. _this._spritesRenderTime.fetchNewFrame();
  100874. }
  100875. if (_this._captureAnimationsTime) {
  100876. _this._animationsTime.beginMonitoring();
  100877. }
  100878. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100879. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100880. });
  100881. // After render
  100882. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100883. if (_this._captureFrameTime) {
  100884. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100885. _this._frameTime.endMonitoring();
  100886. }
  100887. if (_this._captureRenderTime) {
  100888. _this._renderTime.endMonitoring(false);
  100889. }
  100890. if (_this._captureInterFrameTime) {
  100891. _this._interFrameTime.beginMonitoring();
  100892. }
  100893. });
  100894. }
  100895. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100896. // Properties
  100897. /**
  100898. * Gets the perf counter used for active meshes evaluation time
  100899. */
  100900. get: function () {
  100901. return this._activeMeshesEvaluationTime;
  100902. },
  100903. enumerable: true,
  100904. configurable: true
  100905. });
  100906. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100907. /**
  100908. * Gets the active meshes evaluation time capture status
  100909. */
  100910. get: function () {
  100911. return this._captureActiveMeshesEvaluationTime;
  100912. },
  100913. /**
  100914. * Enable or disable the active meshes evaluation time capture
  100915. */
  100916. set: function (value) {
  100917. var _this = this;
  100918. if (value === this._captureActiveMeshesEvaluationTime) {
  100919. return;
  100920. }
  100921. this._captureActiveMeshesEvaluationTime = value;
  100922. if (value) {
  100923. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100924. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100925. _this._activeMeshesEvaluationTime.beginMonitoring();
  100926. });
  100927. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100928. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100929. _this._activeMeshesEvaluationTime.endMonitoring();
  100930. });
  100931. }
  100932. else {
  100933. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100934. this._onBeforeActiveMeshesEvaluationObserver = null;
  100935. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100936. this._onAfterActiveMeshesEvaluationObserver = null;
  100937. }
  100938. },
  100939. enumerable: true,
  100940. configurable: true
  100941. });
  100942. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100943. /**
  100944. * Gets the perf counter used for render targets render time
  100945. */
  100946. get: function () {
  100947. return this._renderTargetsRenderTime;
  100948. },
  100949. enumerable: true,
  100950. configurable: true
  100951. });
  100952. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100953. /**
  100954. * Gets the render targets render time capture status
  100955. */
  100956. get: function () {
  100957. return this._captureRenderTargetsRenderTime;
  100958. },
  100959. /**
  100960. * Enable or disable the render targets render time capture
  100961. */
  100962. set: function (value) {
  100963. var _this = this;
  100964. if (value === this._captureRenderTargetsRenderTime) {
  100965. return;
  100966. }
  100967. this._captureRenderTargetsRenderTime = value;
  100968. if (value) {
  100969. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100970. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100971. _this._renderTargetsRenderTime.beginMonitoring();
  100972. });
  100973. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100974. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100975. _this._renderTargetsRenderTime.endMonitoring(false);
  100976. });
  100977. }
  100978. else {
  100979. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100980. this._onBeforeRenderTargetsRenderObserver = null;
  100981. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100982. this._onAfterRenderTargetsRenderObserver = null;
  100983. }
  100984. },
  100985. enumerable: true,
  100986. configurable: true
  100987. });
  100988. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100989. /**
  100990. * Gets the perf counter used for particles render time
  100991. */
  100992. get: function () {
  100993. return this._particlesRenderTime;
  100994. },
  100995. enumerable: true,
  100996. configurable: true
  100997. });
  100998. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100999. /**
  101000. * Gets the particles render time capture status
  101001. */
  101002. get: function () {
  101003. return this._captureParticlesRenderTime;
  101004. },
  101005. /**
  101006. * Enable or disable the particles render time capture
  101007. */
  101008. set: function (value) {
  101009. var _this = this;
  101010. if (value === this._captureParticlesRenderTime) {
  101011. return;
  101012. }
  101013. this._captureParticlesRenderTime = value;
  101014. if (value) {
  101015. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  101016. BABYLON.Tools.StartPerformanceCounter("Particles");
  101017. _this._particlesRenderTime.beginMonitoring();
  101018. });
  101019. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  101020. BABYLON.Tools.EndPerformanceCounter("Particles");
  101021. _this._particlesRenderTime.endMonitoring(false);
  101022. });
  101023. }
  101024. else {
  101025. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101026. this._onBeforeParticlesRenderingObserver = null;
  101027. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101028. this._onAfterParticlesRenderingObserver = null;
  101029. }
  101030. },
  101031. enumerable: true,
  101032. configurable: true
  101033. });
  101034. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  101035. /**
  101036. * Gets the perf counter used for sprites render time
  101037. */
  101038. get: function () {
  101039. return this._spritesRenderTime;
  101040. },
  101041. enumerable: true,
  101042. configurable: true
  101043. });
  101044. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  101045. /**
  101046. * Gets the sprites render time capture status
  101047. */
  101048. get: function () {
  101049. return this._captureSpritesRenderTime;
  101050. },
  101051. /**
  101052. * Enable or disable the sprites render time capture
  101053. */
  101054. set: function (value) {
  101055. var _this = this;
  101056. if (value === this._captureSpritesRenderTime) {
  101057. return;
  101058. }
  101059. this._captureSpritesRenderTime = value;
  101060. if (value) {
  101061. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  101062. BABYLON.Tools.StartPerformanceCounter("Sprites");
  101063. _this._spritesRenderTime.beginMonitoring();
  101064. });
  101065. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  101066. BABYLON.Tools.EndPerformanceCounter("Sprites");
  101067. _this._spritesRenderTime.endMonitoring(false);
  101068. });
  101069. }
  101070. else {
  101071. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101072. this._onBeforeSpritesRenderingObserver = null;
  101073. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101074. this._onAfterSpritesRenderingObserver = null;
  101075. }
  101076. },
  101077. enumerable: true,
  101078. configurable: true
  101079. });
  101080. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  101081. /**
  101082. * Gets the perf counter used for physics time
  101083. */
  101084. get: function () {
  101085. return this._physicsTime;
  101086. },
  101087. enumerable: true,
  101088. configurable: true
  101089. });
  101090. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  101091. /**
  101092. * Gets the physics time capture status
  101093. */
  101094. get: function () {
  101095. return this._capturePhysicsTime;
  101096. },
  101097. /**
  101098. * Enable or disable the physics time capture
  101099. */
  101100. set: function (value) {
  101101. var _this = this;
  101102. if (value === this._capturePhysicsTime) {
  101103. return;
  101104. }
  101105. this._capturePhysicsTime = value;
  101106. if (value) {
  101107. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  101108. BABYLON.Tools.StartPerformanceCounter("Physics");
  101109. _this._physicsTime.beginMonitoring();
  101110. });
  101111. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  101112. BABYLON.Tools.EndPerformanceCounter("Physics");
  101113. _this._physicsTime.endMonitoring();
  101114. });
  101115. }
  101116. else {
  101117. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101118. this._onBeforePhysicsObserver = null;
  101119. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101120. this._onAfterPhysicsObserver = null;
  101121. }
  101122. },
  101123. enumerable: true,
  101124. configurable: true
  101125. });
  101126. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  101127. /**
  101128. * Gets the perf counter used for animations time
  101129. */
  101130. get: function () {
  101131. return this._animationsTime;
  101132. },
  101133. enumerable: true,
  101134. configurable: true
  101135. });
  101136. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  101137. /**
  101138. * Gets the animations time capture status
  101139. */
  101140. get: function () {
  101141. return this._captureAnimationsTime;
  101142. },
  101143. /**
  101144. * Enable or disable the animations time capture
  101145. */
  101146. set: function (value) {
  101147. var _this = this;
  101148. if (value === this._captureAnimationsTime) {
  101149. return;
  101150. }
  101151. this._captureAnimationsTime = value;
  101152. if (value) {
  101153. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  101154. _this._animationsTime.endMonitoring();
  101155. });
  101156. }
  101157. else {
  101158. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101159. this._onAfterAnimationsObserver = null;
  101160. }
  101161. },
  101162. enumerable: true,
  101163. configurable: true
  101164. });
  101165. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  101166. /**
  101167. * Gets the perf counter used for frame time capture
  101168. */
  101169. get: function () {
  101170. return this._frameTime;
  101171. },
  101172. enumerable: true,
  101173. configurable: true
  101174. });
  101175. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  101176. /**
  101177. * Gets the frame time capture status
  101178. */
  101179. get: function () {
  101180. return this._captureFrameTime;
  101181. },
  101182. /**
  101183. * Enable or disable the frame time capture
  101184. */
  101185. set: function (value) {
  101186. this._captureFrameTime = value;
  101187. },
  101188. enumerable: true,
  101189. configurable: true
  101190. });
  101191. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  101192. /**
  101193. * Gets the perf counter used for inter-frames time capture
  101194. */
  101195. get: function () {
  101196. return this._interFrameTime;
  101197. },
  101198. enumerable: true,
  101199. configurable: true
  101200. });
  101201. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  101202. /**
  101203. * Gets the inter-frames time capture status
  101204. */
  101205. get: function () {
  101206. return this._captureInterFrameTime;
  101207. },
  101208. /**
  101209. * Enable or disable the inter-frames time capture
  101210. */
  101211. set: function (value) {
  101212. this._captureInterFrameTime = value;
  101213. },
  101214. enumerable: true,
  101215. configurable: true
  101216. });
  101217. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  101218. /**
  101219. * Gets the perf counter used for render time capture
  101220. */
  101221. get: function () {
  101222. return this._renderTime;
  101223. },
  101224. enumerable: true,
  101225. configurable: true
  101226. });
  101227. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  101228. /**
  101229. * Gets the render time capture status
  101230. */
  101231. get: function () {
  101232. return this._captureRenderTime;
  101233. },
  101234. /**
  101235. * Enable or disable the render time capture
  101236. */
  101237. set: function (value) {
  101238. var _this = this;
  101239. if (value === this._captureRenderTime) {
  101240. return;
  101241. }
  101242. this._captureRenderTime = value;
  101243. if (value) {
  101244. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  101245. _this._renderTime.beginMonitoring();
  101246. BABYLON.Tools.StartPerformanceCounter("Main render");
  101247. });
  101248. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  101249. _this._renderTime.endMonitoring(false);
  101250. BABYLON.Tools.EndPerformanceCounter("Main render");
  101251. });
  101252. }
  101253. else {
  101254. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101255. this._onBeforeDrawPhaseObserver = null;
  101256. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101257. this._onAfterDrawPhaseObserver = null;
  101258. }
  101259. },
  101260. enumerable: true,
  101261. configurable: true
  101262. });
  101263. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  101264. /**
  101265. * Gets the perf counter used for camera render time capture
  101266. */
  101267. get: function () {
  101268. return this._cameraRenderTime;
  101269. },
  101270. enumerable: true,
  101271. configurable: true
  101272. });
  101273. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  101274. /**
  101275. * Gets the camera render time capture status
  101276. */
  101277. get: function () {
  101278. return this._captureCameraRenderTime;
  101279. },
  101280. /**
  101281. * Enable or disable the camera render time capture
  101282. */
  101283. set: function (value) {
  101284. var _this = this;
  101285. if (value === this._captureCameraRenderTime) {
  101286. return;
  101287. }
  101288. this._captureCameraRenderTime = value;
  101289. if (value) {
  101290. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  101291. _this._cameraRenderTime.beginMonitoring();
  101292. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  101293. });
  101294. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  101295. _this._cameraRenderTime.endMonitoring(false);
  101296. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  101297. });
  101298. }
  101299. else {
  101300. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101301. this._onBeforeCameraRenderObserver = null;
  101302. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101303. this._onAfterCameraRenderObserver = null;
  101304. }
  101305. },
  101306. enumerable: true,
  101307. configurable: true
  101308. });
  101309. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  101310. /**
  101311. * Gets the perf counter used for draw calls
  101312. */
  101313. get: function () {
  101314. return this.scene.getEngine()._drawCalls;
  101315. },
  101316. enumerable: true,
  101317. configurable: true
  101318. });
  101319. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  101320. /**
  101321. * Gets the perf counter used for texture collisions
  101322. */
  101323. get: function () {
  101324. return this.scene.getEngine()._textureCollisions;
  101325. },
  101326. enumerable: true,
  101327. configurable: true
  101328. });
  101329. SceneInstrumentation.prototype.dispose = function () {
  101330. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101331. this._onAfterRenderObserver = null;
  101332. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  101333. this._onBeforeActiveMeshesEvaluationObserver = null;
  101334. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  101335. this._onAfterActiveMeshesEvaluationObserver = null;
  101336. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  101337. this._onBeforeRenderTargetsRenderObserver = null;
  101338. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  101339. this._onAfterRenderTargetsRenderObserver = null;
  101340. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  101341. this._onBeforeAnimationsObserver = null;
  101342. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  101343. this._onBeforeParticlesRenderingObserver = null;
  101344. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  101345. this._onAfterParticlesRenderingObserver = null;
  101346. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  101347. this._onBeforeSpritesRenderingObserver = null;
  101348. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  101349. this._onAfterSpritesRenderingObserver = null;
  101350. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  101351. this._onBeforeDrawPhaseObserver = null;
  101352. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  101353. this._onAfterDrawPhaseObserver = null;
  101354. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  101355. this._onBeforePhysicsObserver = null;
  101356. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  101357. this._onAfterPhysicsObserver = null;
  101358. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  101359. this._onAfterAnimationsObserver = null;
  101360. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  101361. this._onBeforeCameraRenderObserver = null;
  101362. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  101363. this._onAfterCameraRenderObserver = null;
  101364. this.scene = null;
  101365. };
  101366. return SceneInstrumentation;
  101367. }());
  101368. BABYLON.SceneInstrumentation = SceneInstrumentation;
  101369. })(BABYLON || (BABYLON = {}));
  101370. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  101371. var BABYLON;
  101372. (function (BABYLON) {
  101373. /**
  101374. * @hidden
  101375. **/
  101376. var _TimeToken = /** @class */ (function () {
  101377. function _TimeToken() {
  101378. this._timeElapsedQueryEnded = false;
  101379. }
  101380. return _TimeToken;
  101381. }());
  101382. BABYLON._TimeToken = _TimeToken;
  101383. })(BABYLON || (BABYLON = {}));
  101384. //# sourceMappingURL=babylon.timeToken.js.map
  101385. var BABYLON;
  101386. (function (BABYLON) {
  101387. /**
  101388. * Background material defines definition.
  101389. * @hidden Mainly internal Use
  101390. */
  101391. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  101392. __extends(BackgroundMaterialDefines, _super);
  101393. /**
  101394. * Constructor of the defines.
  101395. */
  101396. function BackgroundMaterialDefines() {
  101397. var _this = _super.call(this) || this;
  101398. /**
  101399. * True if the diffuse texture is in use.
  101400. */
  101401. _this.DIFFUSE = false;
  101402. /**
  101403. * The direct UV channel to use.
  101404. */
  101405. _this.DIFFUSEDIRECTUV = 0;
  101406. /**
  101407. * True if the diffuse texture is in gamma space.
  101408. */
  101409. _this.GAMMADIFFUSE = false;
  101410. /**
  101411. * True if the diffuse texture has opacity in the alpha channel.
  101412. */
  101413. _this.DIFFUSEHASALPHA = false;
  101414. /**
  101415. * True if you want the material to fade to transparent at grazing angle.
  101416. */
  101417. _this.OPACITYFRESNEL = false;
  101418. /**
  101419. * True if an extra blur needs to be added in the reflection.
  101420. */
  101421. _this.REFLECTIONBLUR = false;
  101422. /**
  101423. * True if you want the material to fade to reflection at grazing angle.
  101424. */
  101425. _this.REFLECTIONFRESNEL = false;
  101426. /**
  101427. * True if you want the material to falloff as far as you move away from the scene center.
  101428. */
  101429. _this.REFLECTIONFALLOFF = false;
  101430. /**
  101431. * False if the current Webgl implementation does not support the texture lod extension.
  101432. */
  101433. _this.TEXTURELODSUPPORT = false;
  101434. /**
  101435. * True to ensure the data are premultiplied.
  101436. */
  101437. _this.PREMULTIPLYALPHA = false;
  101438. /**
  101439. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101440. */
  101441. _this.USERGBCOLOR = false;
  101442. /**
  101443. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101444. * stays aligned with the desired configuration.
  101445. */
  101446. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101447. /**
  101448. * True to add noise in order to reduce the banding effect.
  101449. */
  101450. _this.NOISE = false;
  101451. /**
  101452. * is the reflection texture in BGR color scheme?
  101453. * Mainly used to solve a bug in ios10 video tag
  101454. */
  101455. _this.REFLECTIONBGR = false;
  101456. _this.IMAGEPROCESSING = false;
  101457. _this.VIGNETTE = false;
  101458. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101459. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101460. _this.TONEMAPPING = false;
  101461. _this.CONTRAST = false;
  101462. _this.COLORCURVES = false;
  101463. _this.COLORGRADING = false;
  101464. _this.COLORGRADING3D = false;
  101465. _this.SAMPLER3DGREENDEPTH = false;
  101466. _this.SAMPLER3DBGRMAP = false;
  101467. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101468. _this.EXPOSURE = false;
  101469. // Reflection.
  101470. _this.REFLECTION = false;
  101471. _this.REFLECTIONMAP_3D = false;
  101472. _this.REFLECTIONMAP_SPHERICAL = false;
  101473. _this.REFLECTIONMAP_PLANAR = false;
  101474. _this.REFLECTIONMAP_CUBIC = false;
  101475. _this.REFLECTIONMAP_PROJECTION = false;
  101476. _this.REFLECTIONMAP_SKYBOX = false;
  101477. _this.REFLECTIONMAP_EXPLICIT = false;
  101478. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101479. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101480. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101481. _this.INVERTCUBICMAP = false;
  101482. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101483. _this.LODINREFLECTIONALPHA = false;
  101484. _this.GAMMAREFLECTION = false;
  101485. _this.RGBDREFLECTION = false;
  101486. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101487. // Default BJS.
  101488. _this.MAINUV1 = false;
  101489. _this.MAINUV2 = false;
  101490. _this.UV1 = false;
  101491. _this.UV2 = false;
  101492. _this.CLIPPLANE = false;
  101493. _this.POINTSIZE = false;
  101494. _this.FOG = false;
  101495. _this.NORMAL = false;
  101496. _this.NUM_BONE_INFLUENCERS = 0;
  101497. _this.BonesPerMesh = 0;
  101498. _this.INSTANCES = false;
  101499. _this.SHADOWFLOAT = false;
  101500. _this.rebuild();
  101501. return _this;
  101502. }
  101503. return BackgroundMaterialDefines;
  101504. }(BABYLON.MaterialDefines));
  101505. /**
  101506. * Background material used to create an efficient environement around your scene.
  101507. */
  101508. var BackgroundMaterial = /** @class */ (function (_super) {
  101509. __extends(BackgroundMaterial, _super);
  101510. /**
  101511. * Instantiates a Background Material in the given scene
  101512. * @param name The friendly name of the material
  101513. * @param scene The scene to add the material to
  101514. */
  101515. function BackgroundMaterial(name, scene) {
  101516. var _this = _super.call(this, name, scene) || this;
  101517. /**
  101518. * Key light Color (multiply against the environement texture)
  101519. */
  101520. _this.primaryColor = BABYLON.Color3.White();
  101521. _this._primaryColorShadowLevel = 0;
  101522. _this._primaryColorHighlightLevel = 0;
  101523. /**
  101524. * Reflection Texture used in the material.
  101525. * Should be author in a specific way for the best result (refer to the documentation).
  101526. */
  101527. _this.reflectionTexture = null;
  101528. /**
  101529. * Reflection Texture level of blur.
  101530. *
  101531. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101532. * texture twice.
  101533. */
  101534. _this.reflectionBlur = 0;
  101535. /**
  101536. * Diffuse Texture used in the material.
  101537. * Should be author in a specific way for the best result (refer to the documentation).
  101538. */
  101539. _this.diffuseTexture = null;
  101540. _this._shadowLights = null;
  101541. /**
  101542. * Specify the list of lights casting shadow on the material.
  101543. * All scene shadow lights will be included if null.
  101544. */
  101545. _this.shadowLights = null;
  101546. /**
  101547. * Helps adjusting the shadow to a softer level if required.
  101548. * 0 means black shadows and 1 means no shadows.
  101549. */
  101550. _this.shadowLevel = 0;
  101551. /**
  101552. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101553. * It is usually zero but might be interesting to modify according to your setup.
  101554. */
  101555. _this.sceneCenter = BABYLON.Vector3.Zero();
  101556. /**
  101557. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101558. * This helps ensuring a nice transition when the camera goes under the ground.
  101559. */
  101560. _this.opacityFresnel = true;
  101561. /**
  101562. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101563. * This helps adding a mirror texture on the ground.
  101564. */
  101565. _this.reflectionFresnel = false;
  101566. /**
  101567. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101568. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101569. */
  101570. _this.reflectionFalloffDistance = 0.0;
  101571. /**
  101572. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101573. */
  101574. _this.reflectionAmount = 1.0;
  101575. /**
  101576. * This specifies the weight of the reflection at grazing angle.
  101577. */
  101578. _this.reflectionReflectance0 = 0.05;
  101579. /**
  101580. * This specifies the weight of the reflection at a perpendicular point of view.
  101581. */
  101582. _this.reflectionReflectance90 = 0.5;
  101583. /**
  101584. * Helps to directly use the maps channels instead of their level.
  101585. */
  101586. _this.useRGBColor = true;
  101587. /**
  101588. * This helps reducing the banding effect that could occur on the background.
  101589. */
  101590. _this.enableNoise = false;
  101591. _this._fovMultiplier = 1.0;
  101592. /**
  101593. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101594. */
  101595. _this.useEquirectangularFOV = false;
  101596. _this._maxSimultaneousLights = 4;
  101597. /**
  101598. * Number of Simultaneous lights allowed on the material.
  101599. */
  101600. _this.maxSimultaneousLights = 4;
  101601. /**
  101602. * Keep track of the image processing observer to allow dispose and replace.
  101603. */
  101604. _this._imageProcessingObserver = null;
  101605. /**
  101606. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101607. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101608. */
  101609. _this.switchToBGR = false;
  101610. // Temp values kept as cache in the material.
  101611. _this._renderTargets = new BABYLON.SmartArray(16);
  101612. _this._reflectionControls = BABYLON.Vector4.Zero();
  101613. _this._white = BABYLON.Color3.White();
  101614. _this._primaryShadowColor = BABYLON.Color3.Black();
  101615. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101616. // Setup the default processing configuration to the scene.
  101617. _this._attachImageProcessingConfiguration(null);
  101618. _this.getRenderTargetTextures = function () {
  101619. _this._renderTargets.reset();
  101620. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101621. _this._renderTargets.push(_this._diffuseTexture);
  101622. }
  101623. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101624. _this._renderTargets.push(_this._reflectionTexture);
  101625. }
  101626. return _this._renderTargets;
  101627. };
  101628. return _this;
  101629. }
  101630. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101631. /**
  101632. * Experimental Internal Use Only.
  101633. *
  101634. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101635. * This acts as a helper to set the primary color to a more "human friendly" value.
  101636. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101637. * output color as close as possible from the chosen value.
  101638. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101639. * part of lighting setup.)
  101640. */
  101641. get: function () {
  101642. return this.__perceptualColor;
  101643. },
  101644. set: function (value) {
  101645. this.__perceptualColor = value;
  101646. this._computePrimaryColorFromPerceptualColor();
  101647. this._markAllSubMeshesAsLightsDirty();
  101648. },
  101649. enumerable: true,
  101650. configurable: true
  101651. });
  101652. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101653. /**
  101654. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101655. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101656. */
  101657. get: function () {
  101658. return this._primaryColorShadowLevel;
  101659. },
  101660. set: function (value) {
  101661. this._primaryColorShadowLevel = value;
  101662. this._computePrimaryColors();
  101663. this._markAllSubMeshesAsLightsDirty();
  101664. },
  101665. enumerable: true,
  101666. configurable: true
  101667. });
  101668. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101669. /**
  101670. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101671. * The primary color is used at the level chosen to define what the white area would look.
  101672. */
  101673. get: function () {
  101674. return this._primaryColorHighlightLevel;
  101675. },
  101676. set: function (value) {
  101677. this._primaryColorHighlightLevel = value;
  101678. this._computePrimaryColors();
  101679. this._markAllSubMeshesAsLightsDirty();
  101680. },
  101681. enumerable: true,
  101682. configurable: true
  101683. });
  101684. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101685. /**
  101686. * Sets the reflection reflectance fresnel values according to the default standard
  101687. * empirically know to work well :-)
  101688. */
  101689. set: function (value) {
  101690. var reflectionWeight = value;
  101691. if (reflectionWeight < 0.5) {
  101692. reflectionWeight = reflectionWeight * 2.0;
  101693. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101694. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101695. }
  101696. else {
  101697. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101698. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101699. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101700. }
  101701. },
  101702. enumerable: true,
  101703. configurable: true
  101704. });
  101705. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101706. /**
  101707. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101708. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101709. * Recommended to be keep at 1.0 except for special cases.
  101710. */
  101711. get: function () {
  101712. return this._fovMultiplier;
  101713. },
  101714. set: function (value) {
  101715. if (isNaN(value)) {
  101716. value = 1.0;
  101717. }
  101718. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101719. },
  101720. enumerable: true,
  101721. configurable: true
  101722. });
  101723. /**
  101724. * Attaches a new image processing configuration to the PBR Material.
  101725. * @param configuration (if null the scene configuration will be use)
  101726. */
  101727. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101728. var _this = this;
  101729. if (configuration === this._imageProcessingConfiguration) {
  101730. return;
  101731. }
  101732. // Detaches observer.
  101733. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101734. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101735. }
  101736. // Pick the scene configuration if needed.
  101737. if (!configuration) {
  101738. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101739. }
  101740. else {
  101741. this._imageProcessingConfiguration = configuration;
  101742. }
  101743. // Attaches observer.
  101744. if (this._imageProcessingConfiguration) {
  101745. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101746. _this._computePrimaryColorFromPerceptualColor();
  101747. _this._markAllSubMeshesAsImageProcessingDirty();
  101748. });
  101749. }
  101750. };
  101751. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101752. /**
  101753. * Gets the image processing configuration used either in this material.
  101754. */
  101755. get: function () {
  101756. return this._imageProcessingConfiguration;
  101757. },
  101758. /**
  101759. * Sets the Default image processing configuration used either in the this material.
  101760. *
  101761. * If sets to null, the scene one is in use.
  101762. */
  101763. set: function (value) {
  101764. this._attachImageProcessingConfiguration(value);
  101765. // Ensure the effect will be rebuilt.
  101766. this._markAllSubMeshesAsTexturesDirty();
  101767. },
  101768. enumerable: true,
  101769. configurable: true
  101770. });
  101771. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101772. /**
  101773. * Gets wether the color curves effect is enabled.
  101774. */
  101775. get: function () {
  101776. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101777. },
  101778. /**
  101779. * Sets wether the color curves effect is enabled.
  101780. */
  101781. set: function (value) {
  101782. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101783. },
  101784. enumerable: true,
  101785. configurable: true
  101786. });
  101787. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101788. /**
  101789. * Gets wether the color grading effect is enabled.
  101790. */
  101791. get: function () {
  101792. return this.imageProcessingConfiguration.colorGradingEnabled;
  101793. },
  101794. /**
  101795. * Gets wether the color grading effect is enabled.
  101796. */
  101797. set: function (value) {
  101798. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101799. },
  101800. enumerable: true,
  101801. configurable: true
  101802. });
  101803. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101804. /**
  101805. * Gets wether tonemapping is enabled or not.
  101806. */
  101807. get: function () {
  101808. return this._imageProcessingConfiguration.toneMappingEnabled;
  101809. },
  101810. /**
  101811. * Sets wether tonemapping is enabled or not
  101812. */
  101813. set: function (value) {
  101814. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101815. },
  101816. enumerable: true,
  101817. configurable: true
  101818. });
  101819. ;
  101820. ;
  101821. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101822. /**
  101823. * The camera exposure used on this material.
  101824. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101825. * This corresponds to a photographic exposure.
  101826. */
  101827. get: function () {
  101828. return this._imageProcessingConfiguration.exposure;
  101829. },
  101830. /**
  101831. * The camera exposure used on this material.
  101832. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101833. * This corresponds to a photographic exposure.
  101834. */
  101835. set: function (value) {
  101836. this._imageProcessingConfiguration.exposure = value;
  101837. },
  101838. enumerable: true,
  101839. configurable: true
  101840. });
  101841. ;
  101842. ;
  101843. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101844. /**
  101845. * Gets The camera contrast used on this material.
  101846. */
  101847. get: function () {
  101848. return this._imageProcessingConfiguration.contrast;
  101849. },
  101850. /**
  101851. * Sets The camera contrast used on this material.
  101852. */
  101853. set: function (value) {
  101854. this._imageProcessingConfiguration.contrast = value;
  101855. },
  101856. enumerable: true,
  101857. configurable: true
  101858. });
  101859. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101860. /**
  101861. * Gets the Color Grading 2D Lookup Texture.
  101862. */
  101863. get: function () {
  101864. return this._imageProcessingConfiguration.colorGradingTexture;
  101865. },
  101866. /**
  101867. * Sets the Color Grading 2D Lookup Texture.
  101868. */
  101869. set: function (value) {
  101870. this.imageProcessingConfiguration.colorGradingTexture = value;
  101871. },
  101872. enumerable: true,
  101873. configurable: true
  101874. });
  101875. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101876. /**
  101877. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101878. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101879. * 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;
  101880. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101881. */
  101882. get: function () {
  101883. return this.imageProcessingConfiguration.colorCurves;
  101884. },
  101885. /**
  101886. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101887. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101888. * 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;
  101889. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101890. */
  101891. set: function (value) {
  101892. this.imageProcessingConfiguration.colorCurves = value;
  101893. },
  101894. enumerable: true,
  101895. configurable: true
  101896. });
  101897. /**
  101898. * The entire material has been created in order to prevent overdraw.
  101899. * @returns false
  101900. */
  101901. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101902. return true;
  101903. };
  101904. /**
  101905. * The entire material has been created in order to prevent overdraw.
  101906. * @returns true if blending is enable
  101907. */
  101908. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101909. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101910. };
  101911. /**
  101912. * Checks wether the material is ready to be rendered for a given mesh.
  101913. * @param mesh The mesh to render
  101914. * @param subMesh The submesh to check against
  101915. * @param useInstances Specify wether or not the material is used with instances
  101916. * @returns true if all the dependencies are ready (Textures, Effects...)
  101917. */
  101918. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101919. var _this = this;
  101920. if (useInstances === void 0) { useInstances = false; }
  101921. if (subMesh.effect && this.isFrozen) {
  101922. if (this._wasPreviouslyReady) {
  101923. return true;
  101924. }
  101925. }
  101926. if (!subMesh._materialDefines) {
  101927. subMesh._materialDefines = new BackgroundMaterialDefines();
  101928. }
  101929. var scene = this.getScene();
  101930. var defines = subMesh._materialDefines;
  101931. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101932. if (defines._renderId === scene.getRenderId()) {
  101933. return true;
  101934. }
  101935. }
  101936. var engine = scene.getEngine();
  101937. // Lights
  101938. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101939. defines._needNormals = true;
  101940. // Textures
  101941. if (defines._areTexturesDirty) {
  101942. defines._needUVs = false;
  101943. if (scene.texturesEnabled) {
  101944. if (scene.getEngine().getCaps().textureLOD) {
  101945. defines.TEXTURELODSUPPORT = true;
  101946. }
  101947. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101948. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101949. return false;
  101950. }
  101951. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101952. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101953. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101954. defines.OPACITYFRESNEL = this._opacityFresnel;
  101955. }
  101956. else {
  101957. defines.DIFFUSE = false;
  101958. defines.DIFFUSEHASALPHA = false;
  101959. defines.GAMMADIFFUSE = false;
  101960. defines.OPACITYFRESNEL = false;
  101961. }
  101962. var reflectionTexture = this._reflectionTexture;
  101963. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101964. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101965. return false;
  101966. }
  101967. defines.REFLECTION = true;
  101968. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101969. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101970. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101971. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101972. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101973. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101974. defines.REFLECTIONBGR = this.switchToBGR;
  101975. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101976. defines.INVERTCUBICMAP = true;
  101977. }
  101978. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101979. switch (reflectionTexture.coordinatesMode) {
  101980. case BABYLON.Texture.EXPLICIT_MODE:
  101981. defines.REFLECTIONMAP_EXPLICIT = true;
  101982. break;
  101983. case BABYLON.Texture.PLANAR_MODE:
  101984. defines.REFLECTIONMAP_PLANAR = true;
  101985. break;
  101986. case BABYLON.Texture.PROJECTION_MODE:
  101987. defines.REFLECTIONMAP_PROJECTION = true;
  101988. break;
  101989. case BABYLON.Texture.SKYBOX_MODE:
  101990. defines.REFLECTIONMAP_SKYBOX = true;
  101991. break;
  101992. case BABYLON.Texture.SPHERICAL_MODE:
  101993. defines.REFLECTIONMAP_SPHERICAL = true;
  101994. break;
  101995. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101996. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101997. break;
  101998. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101999. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  102000. break;
  102001. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  102002. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  102003. break;
  102004. case BABYLON.Texture.CUBIC_MODE:
  102005. case BABYLON.Texture.INVCUBIC_MODE:
  102006. default:
  102007. defines.REFLECTIONMAP_CUBIC = true;
  102008. break;
  102009. }
  102010. if (this.reflectionFresnel) {
  102011. defines.REFLECTIONFRESNEL = true;
  102012. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  102013. this._reflectionControls.x = this.reflectionAmount;
  102014. this._reflectionControls.y = this.reflectionReflectance0;
  102015. this._reflectionControls.z = this.reflectionReflectance90;
  102016. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  102017. }
  102018. else {
  102019. defines.REFLECTIONFRESNEL = false;
  102020. defines.REFLECTIONFALLOFF = false;
  102021. }
  102022. }
  102023. else {
  102024. defines.REFLECTION = false;
  102025. defines.REFLECTIONFRESNEL = false;
  102026. defines.REFLECTIONFALLOFF = false;
  102027. defines.REFLECTIONBLUR = false;
  102028. defines.REFLECTIONMAP_3D = false;
  102029. defines.REFLECTIONMAP_SPHERICAL = false;
  102030. defines.REFLECTIONMAP_PLANAR = false;
  102031. defines.REFLECTIONMAP_CUBIC = false;
  102032. defines.REFLECTIONMAP_PROJECTION = false;
  102033. defines.REFLECTIONMAP_SKYBOX = false;
  102034. defines.REFLECTIONMAP_EXPLICIT = false;
  102035. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  102036. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  102037. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  102038. defines.INVERTCUBICMAP = false;
  102039. defines.REFLECTIONMAP_OPPOSITEZ = false;
  102040. defines.LODINREFLECTIONALPHA = false;
  102041. defines.GAMMAREFLECTION = false;
  102042. defines.RGBDREFLECTION = false;
  102043. }
  102044. }
  102045. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  102046. defines.USERGBCOLOR = this._useRGBColor;
  102047. defines.NOISE = this._enableNoise;
  102048. }
  102049. if (defines._areLightsDirty) {
  102050. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  102051. }
  102052. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  102053. if (!this._imageProcessingConfiguration.isReady()) {
  102054. return false;
  102055. }
  102056. this._imageProcessingConfiguration.prepareDefines(defines);
  102057. }
  102058. // Misc.
  102059. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  102060. // Values that need to be evaluated on every frame
  102061. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  102062. // Attribs
  102063. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  102064. if (mesh) {
  102065. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  102066. mesh.createNormals(true);
  102067. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  102068. }
  102069. }
  102070. }
  102071. // Get correct effect
  102072. if (defines.isDirty) {
  102073. defines.markAsProcessed();
  102074. scene.resetCachedMaterial();
  102075. // Fallbacks
  102076. var fallbacks = new BABYLON.EffectFallbacks();
  102077. if (defines.FOG) {
  102078. fallbacks.addFallback(0, "FOG");
  102079. }
  102080. if (defines.POINTSIZE) {
  102081. fallbacks.addFallback(1, "POINTSIZE");
  102082. }
  102083. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  102084. if (defines.NUM_BONE_INFLUENCERS > 0) {
  102085. fallbacks.addCPUSkinningFallback(0, mesh);
  102086. }
  102087. //Attributes
  102088. var attribs = [BABYLON.VertexBuffer.PositionKind];
  102089. if (defines.NORMAL) {
  102090. attribs.push(BABYLON.VertexBuffer.NormalKind);
  102091. }
  102092. if (defines.UV1) {
  102093. attribs.push(BABYLON.VertexBuffer.UVKind);
  102094. }
  102095. if (defines.UV2) {
  102096. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  102097. }
  102098. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  102099. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  102100. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  102101. "vFogInfos", "vFogColor", "pointSize",
  102102. "vClipPlane", "mBones",
  102103. "vPrimaryColor", "vPrimaryColorShadow",
  102104. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  102105. "shadowLevel", "alpha",
  102106. "vBackgroundCenter", "vReflectionControl",
  102107. "vDiffuseInfos", "diffuseMatrix",
  102108. ];
  102109. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  102110. var uniformBuffers = ["Material", "Scene"];
  102111. if (BABYLON.ImageProcessingConfiguration) {
  102112. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  102113. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  102114. }
  102115. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  102116. uniformsNames: uniforms,
  102117. uniformBuffersNames: uniformBuffers,
  102118. samplers: samplers,
  102119. defines: defines,
  102120. maxSimultaneousLights: this._maxSimultaneousLights
  102121. });
  102122. var onCompiled = function (effect) {
  102123. if (_this.onCompiled) {
  102124. _this.onCompiled(effect);
  102125. }
  102126. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  102127. };
  102128. var join = defines.toString();
  102129. subMesh.setEffect(scene.getEngine().createEffect("background", {
  102130. attributes: attribs,
  102131. uniformsNames: uniforms,
  102132. uniformBuffersNames: uniformBuffers,
  102133. samplers: samplers,
  102134. defines: join,
  102135. fallbacks: fallbacks,
  102136. onCompiled: onCompiled,
  102137. onError: this.onError,
  102138. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  102139. }, engine), defines);
  102140. this.buildUniformLayout();
  102141. }
  102142. if (!subMesh.effect || !subMesh.effect.isReady()) {
  102143. return false;
  102144. }
  102145. defines._renderId = scene.getRenderId();
  102146. this._wasPreviouslyReady = true;
  102147. return true;
  102148. };
  102149. /**
  102150. * Compute the primary color according to the chosen perceptual color.
  102151. */
  102152. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  102153. if (!this.__perceptualColor) {
  102154. return;
  102155. }
  102156. this._primaryColor.copyFrom(this.__perceptualColor);
  102157. // Revert gamma space.
  102158. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  102159. // Revert image processing configuration.
  102160. if (this._imageProcessingConfiguration) {
  102161. // Revert Exposure.
  102162. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  102163. }
  102164. this._computePrimaryColors();
  102165. };
  102166. /**
  102167. * Compute the highlights and shadow colors according to their chosen levels.
  102168. */
  102169. BackgroundMaterial.prototype._computePrimaryColors = function () {
  102170. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  102171. return;
  102172. }
  102173. // Find the highlight color based on the configuration.
  102174. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  102175. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  102176. // Find the shadow color based on the configuration.
  102177. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  102178. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  102179. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  102180. };
  102181. /**
  102182. * Build the uniform buffer used in the material.
  102183. */
  102184. BackgroundMaterial.prototype.buildUniformLayout = function () {
  102185. // Order is important !
  102186. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  102187. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  102188. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  102189. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  102190. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  102191. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  102192. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  102193. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  102194. this._uniformBuffer.addUniform("pointSize", 1);
  102195. this._uniformBuffer.addUniform("shadowLevel", 1);
  102196. this._uniformBuffer.addUniform("alpha", 1);
  102197. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  102198. this._uniformBuffer.addUniform("vReflectionControl", 4);
  102199. this._uniformBuffer.create();
  102200. };
  102201. /**
  102202. * Unbind the material.
  102203. */
  102204. BackgroundMaterial.prototype.unbind = function () {
  102205. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  102206. this._uniformBuffer.setTexture("diffuseSampler", null);
  102207. }
  102208. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  102209. this._uniformBuffer.setTexture("reflectionSampler", null);
  102210. }
  102211. _super.prototype.unbind.call(this);
  102212. };
  102213. /**
  102214. * Bind only the world matrix to the material.
  102215. * @param world The world matrix to bind.
  102216. */
  102217. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  102218. this._activeEffect.setMatrix("world", world);
  102219. };
  102220. /**
  102221. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  102222. * @param world The world matrix to bind.
  102223. * @param subMesh The submesh to bind for.
  102224. */
  102225. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  102226. var scene = this.getScene();
  102227. var defines = subMesh._materialDefines;
  102228. if (!defines) {
  102229. return;
  102230. }
  102231. var effect = subMesh.effect;
  102232. if (!effect) {
  102233. return;
  102234. }
  102235. this._activeEffect = effect;
  102236. // Matrices
  102237. this.bindOnlyWorldMatrix(world);
  102238. // Bones
  102239. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  102240. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  102241. if (mustRebind) {
  102242. this._uniformBuffer.bindToEffect(effect, "Material");
  102243. this.bindViewProjection(effect);
  102244. var reflectionTexture = this._reflectionTexture;
  102245. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  102246. // Texture uniforms
  102247. if (scene.texturesEnabled) {
  102248. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102249. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  102250. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  102251. }
  102252. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102253. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  102254. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  102255. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  102256. }
  102257. }
  102258. if (this.shadowLevel > 0) {
  102259. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  102260. }
  102261. this._uniformBuffer.updateFloat("alpha", this.alpha);
  102262. // Point size
  102263. if (this.pointsCloud) {
  102264. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  102265. }
  102266. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  102267. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  102268. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  102269. }
  102270. else {
  102271. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  102272. }
  102273. }
  102274. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  102275. // Textures
  102276. if (scene.texturesEnabled) {
  102277. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  102278. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  102279. }
  102280. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  102281. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  102282. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102283. }
  102284. else if (!defines.REFLECTIONBLUR) {
  102285. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  102286. }
  102287. else {
  102288. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  102289. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  102290. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  102291. }
  102292. if (defines.REFLECTIONFRESNEL) {
  102293. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  102294. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  102295. }
  102296. }
  102297. }
  102298. // Clip plane
  102299. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  102300. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  102301. }
  102302. if (mustRebind || !this.isFrozen) {
  102303. if (scene.lightsEnabled) {
  102304. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  102305. }
  102306. // View
  102307. this.bindView(effect);
  102308. // Fog
  102309. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  102310. // image processing
  102311. if (this._imageProcessingConfiguration) {
  102312. this._imageProcessingConfiguration.bind(this._activeEffect);
  102313. }
  102314. }
  102315. this._uniformBuffer.update();
  102316. this._afterBind(mesh, this._activeEffect);
  102317. };
  102318. /**
  102319. * Dispose the material.
  102320. * @param forceDisposeEffect Force disposal of the associated effect.
  102321. * @param forceDisposeTextures Force disposal of the associated textures.
  102322. */
  102323. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  102324. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  102325. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  102326. if (forceDisposeTextures) {
  102327. if (this.diffuseTexture) {
  102328. this.diffuseTexture.dispose();
  102329. }
  102330. if (this.reflectionTexture) {
  102331. this.reflectionTexture.dispose();
  102332. }
  102333. }
  102334. this._renderTargets.dispose();
  102335. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  102336. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  102337. }
  102338. _super.prototype.dispose.call(this, forceDisposeEffect);
  102339. };
  102340. /**
  102341. * Clones the material.
  102342. * @param name The cloned name.
  102343. * @returns The cloned material.
  102344. */
  102345. BackgroundMaterial.prototype.clone = function (name) {
  102346. var _this = this;
  102347. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  102348. };
  102349. /**
  102350. * Serializes the current material to its JSON representation.
  102351. * @returns The JSON representation.
  102352. */
  102353. BackgroundMaterial.prototype.serialize = function () {
  102354. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  102355. serializationObject.customType = "BABYLON.BackgroundMaterial";
  102356. return serializationObject;
  102357. };
  102358. /**
  102359. * Gets the class name of the material
  102360. * @returns "BackgroundMaterial"
  102361. */
  102362. BackgroundMaterial.prototype.getClassName = function () {
  102363. return "BackgroundMaterial";
  102364. };
  102365. /**
  102366. * Parse a JSON input to create back a background material.
  102367. * @param source The JSON data to parse
  102368. * @param scene The scene to create the parsed material in
  102369. * @param rootUrl The root url of the assets the material depends upon
  102370. * @returns the instantiated BackgroundMaterial.
  102371. */
  102372. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  102373. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  102374. };
  102375. /**
  102376. * Standard reflectance value at parallel view angle.
  102377. */
  102378. BackgroundMaterial.StandardReflectance0 = 0.05;
  102379. /**
  102380. * Standard reflectance value at grazing angle.
  102381. */
  102382. BackgroundMaterial.StandardReflectance90 = 0.5;
  102383. __decorate([
  102384. BABYLON.serializeAsColor3()
  102385. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  102386. __decorate([
  102387. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102388. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  102389. __decorate([
  102390. BABYLON.serializeAsColor3()
  102391. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  102392. __decorate([
  102393. BABYLON.serialize()
  102394. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  102395. __decorate([
  102396. BABYLON.serialize()
  102397. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  102398. __decorate([
  102399. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  102400. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  102401. __decorate([
  102402. BABYLON.serializeAsTexture()
  102403. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  102404. __decorate([
  102405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102406. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  102407. __decorate([
  102408. BABYLON.serialize()
  102409. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102410. __decorate([
  102411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102412. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102413. __decorate([
  102414. BABYLON.serializeAsTexture()
  102415. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102416. __decorate([
  102417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102418. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102419. __decorate([
  102420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102421. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102422. __decorate([
  102423. BABYLON.serialize()
  102424. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102425. __decorate([
  102426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102427. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102428. __decorate([
  102429. BABYLON.serializeAsVector3()
  102430. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102431. __decorate([
  102432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102433. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102434. __decorate([
  102435. BABYLON.serialize()
  102436. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102437. __decorate([
  102438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102439. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102440. __decorate([
  102441. BABYLON.serialize()
  102442. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102443. __decorate([
  102444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102445. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102446. __decorate([
  102447. BABYLON.serialize()
  102448. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102449. __decorate([
  102450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102451. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102452. __decorate([
  102453. BABYLON.serialize()
  102454. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102455. __decorate([
  102456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102457. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102458. __decorate([
  102459. BABYLON.serialize()
  102460. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102461. __decorate([
  102462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102463. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102464. __decorate([
  102465. BABYLON.serialize()
  102466. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102467. __decorate([
  102468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102469. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102470. __decorate([
  102471. BABYLON.serialize()
  102472. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102473. __decorate([
  102474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102475. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102476. __decorate([
  102477. BABYLON.serialize()
  102478. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102479. __decorate([
  102480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102481. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102482. __decorate([
  102483. BABYLON.serialize()
  102484. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102485. __decorate([
  102486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102487. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102488. __decorate([
  102489. BABYLON.serializeAsImageProcessingConfiguration()
  102490. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102491. return BackgroundMaterial;
  102492. }(BABYLON.PushMaterial));
  102493. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102494. })(BABYLON || (BABYLON = {}));
  102495. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102496. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102497. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102498. s = arguments[i];
  102499. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102500. t[p] = s[p];
  102501. }
  102502. return t;
  102503. };
  102504. var BABYLON;
  102505. (function (BABYLON) {
  102506. /**
  102507. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102508. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102509. * It also helps with the default setup of your imageProcessing configuration.
  102510. */
  102511. var EnvironmentHelper = /** @class */ (function () {
  102512. /**
  102513. * constructor
  102514. * @param options
  102515. * @param scene The scene to add the material to
  102516. */
  102517. function EnvironmentHelper(options, scene) {
  102518. var _this = this;
  102519. this._errorHandler = function (message, exception) {
  102520. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102521. };
  102522. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102523. this._scene = scene;
  102524. this.onErrorObservable = new BABYLON.Observable();
  102525. this._setupBackground();
  102526. this._setupImageProcessing();
  102527. }
  102528. /**
  102529. * Creates the default options for the helper.
  102530. */
  102531. EnvironmentHelper._getDefaultOptions = function () {
  102532. return {
  102533. createGround: true,
  102534. groundSize: 15,
  102535. groundTexture: this._groundTextureCDNUrl,
  102536. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102537. groundOpacity: 0.9,
  102538. enableGroundShadow: true,
  102539. groundShadowLevel: 0.5,
  102540. enableGroundMirror: false,
  102541. groundMirrorSizeRatio: 0.3,
  102542. groundMirrorBlurKernel: 64,
  102543. groundMirrorAmount: 1,
  102544. groundMirrorFresnelWeight: 1,
  102545. groundMirrorFallOffDistance: 0,
  102546. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102547. groundYBias: 0.00001,
  102548. createSkybox: true,
  102549. skyboxSize: 20,
  102550. skyboxTexture: this._skyboxTextureCDNUrl,
  102551. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102552. backgroundYRotation: 0,
  102553. sizeAuto: true,
  102554. rootPosition: BABYLON.Vector3.Zero(),
  102555. setupImageProcessing: true,
  102556. environmentTexture: this._environmentTextureCDNUrl,
  102557. cameraExposure: 0.8,
  102558. cameraContrast: 1.2,
  102559. toneMappingEnabled: true,
  102560. };
  102561. };
  102562. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102563. /**
  102564. * Gets the root mesh created by the helper.
  102565. */
  102566. get: function () {
  102567. return this._rootMesh;
  102568. },
  102569. enumerable: true,
  102570. configurable: true
  102571. });
  102572. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102573. /**
  102574. * Gets the skybox created by the helper.
  102575. */
  102576. get: function () {
  102577. return this._skybox;
  102578. },
  102579. enumerable: true,
  102580. configurable: true
  102581. });
  102582. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102583. /**
  102584. * Gets the skybox texture created by the helper.
  102585. */
  102586. get: function () {
  102587. return this._skyboxTexture;
  102588. },
  102589. enumerable: true,
  102590. configurable: true
  102591. });
  102592. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102593. /**
  102594. * Gets the skybox material created by the helper.
  102595. */
  102596. get: function () {
  102597. return this._skyboxMaterial;
  102598. },
  102599. enumerable: true,
  102600. configurable: true
  102601. });
  102602. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102603. /**
  102604. * Gets the ground mesh created by the helper.
  102605. */
  102606. get: function () {
  102607. return this._ground;
  102608. },
  102609. enumerable: true,
  102610. configurable: true
  102611. });
  102612. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102613. /**
  102614. * Gets the ground texture created by the helper.
  102615. */
  102616. get: function () {
  102617. return this._groundTexture;
  102618. },
  102619. enumerable: true,
  102620. configurable: true
  102621. });
  102622. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102623. /**
  102624. * Gets the ground mirror created by the helper.
  102625. */
  102626. get: function () {
  102627. return this._groundMirror;
  102628. },
  102629. enumerable: true,
  102630. configurable: true
  102631. });
  102632. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102633. /**
  102634. * Gets the ground mirror render list to helps pushing the meshes
  102635. * you wish in the ground reflection.
  102636. */
  102637. get: function () {
  102638. if (this._groundMirror) {
  102639. return this._groundMirror.renderList;
  102640. }
  102641. return null;
  102642. },
  102643. enumerable: true,
  102644. configurable: true
  102645. });
  102646. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102647. /**
  102648. * Gets the ground material created by the helper.
  102649. */
  102650. get: function () {
  102651. return this._groundMaterial;
  102652. },
  102653. enumerable: true,
  102654. configurable: true
  102655. });
  102656. /**
  102657. * Updates the background according to the new options
  102658. * @param options
  102659. */
  102660. EnvironmentHelper.prototype.updateOptions = function (options) {
  102661. var newOptions = __assign({}, this._options, options);
  102662. if (this._ground && !newOptions.createGround) {
  102663. this._ground.dispose();
  102664. this._ground = null;
  102665. }
  102666. if (this._groundMaterial && !newOptions.createGround) {
  102667. this._groundMaterial.dispose();
  102668. this._groundMaterial = null;
  102669. }
  102670. if (this._groundTexture) {
  102671. if (this._options.groundTexture != newOptions.groundTexture) {
  102672. this._groundTexture.dispose();
  102673. this._groundTexture = null;
  102674. }
  102675. }
  102676. if (this._skybox && !newOptions.createSkybox) {
  102677. this._skybox.dispose();
  102678. this._skybox = null;
  102679. }
  102680. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102681. this._skyboxMaterial.dispose();
  102682. this._skyboxMaterial = null;
  102683. }
  102684. if (this._skyboxTexture) {
  102685. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102686. this._skyboxTexture.dispose();
  102687. this._skyboxTexture = null;
  102688. }
  102689. }
  102690. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102691. this._groundMirror.dispose();
  102692. this._groundMirror = null;
  102693. }
  102694. if (this._scene.environmentTexture) {
  102695. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102696. this._scene.environmentTexture.dispose();
  102697. }
  102698. }
  102699. this._options = newOptions;
  102700. this._setupBackground();
  102701. this._setupImageProcessing();
  102702. };
  102703. /**
  102704. * Sets the primary color of all the available elements.
  102705. * @param color the main color to affect to the ground and the background
  102706. */
  102707. EnvironmentHelper.prototype.setMainColor = function (color) {
  102708. if (this.groundMaterial) {
  102709. this.groundMaterial.primaryColor = color;
  102710. }
  102711. if (this.skyboxMaterial) {
  102712. this.skyboxMaterial.primaryColor = color;
  102713. }
  102714. if (this.groundMirror) {
  102715. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102716. }
  102717. };
  102718. /**
  102719. * Setup the image processing according to the specified options.
  102720. */
  102721. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102722. if (this._options.setupImageProcessing) {
  102723. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102724. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102725. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102726. this._setupEnvironmentTexture();
  102727. }
  102728. };
  102729. /**
  102730. * Setup the environment texture according to the specified options.
  102731. */
  102732. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102733. if (this._scene.environmentTexture) {
  102734. return;
  102735. }
  102736. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102737. this._scene.environmentTexture = this._options.environmentTexture;
  102738. return;
  102739. }
  102740. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102741. this._scene.environmentTexture = environmentTexture;
  102742. };
  102743. /**
  102744. * Setup the background according to the specified options.
  102745. */
  102746. EnvironmentHelper.prototype._setupBackground = function () {
  102747. if (!this._rootMesh) {
  102748. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102749. }
  102750. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102751. var sceneSize = this._getSceneSize();
  102752. if (this._options.createGround) {
  102753. this._setupGround(sceneSize);
  102754. this._setupGroundMaterial();
  102755. this._setupGroundDiffuseTexture();
  102756. if (this._options.enableGroundMirror) {
  102757. this._setupGroundMirrorTexture(sceneSize);
  102758. }
  102759. this._setupMirrorInGroundMaterial();
  102760. }
  102761. if (this._options.createSkybox) {
  102762. this._setupSkybox(sceneSize);
  102763. this._setupSkyboxMaterial();
  102764. this._setupSkyboxReflectionTexture();
  102765. }
  102766. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102767. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102768. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102769. };
  102770. /**
  102771. * Get the scene sizes according to the setup.
  102772. */
  102773. EnvironmentHelper.prototype._getSceneSize = function () {
  102774. var _this = this;
  102775. var groundSize = this._options.groundSize;
  102776. var skyboxSize = this._options.skyboxSize;
  102777. var rootPosition = this._options.rootPosition;
  102778. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102779. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102780. }
  102781. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102782. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102783. });
  102784. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102785. if (this._options.sizeAuto) {
  102786. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102787. this._scene.activeCamera.upperRadiusLimit) {
  102788. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102789. skyboxSize = groundSize;
  102790. }
  102791. var sceneDiagonalLenght = sceneDiagonal.length();
  102792. if (sceneDiagonalLenght > groundSize) {
  102793. groundSize = sceneDiagonalLenght * 2;
  102794. skyboxSize = groundSize;
  102795. }
  102796. // 10 % bigger.
  102797. groundSize *= 1.1;
  102798. skyboxSize *= 1.5;
  102799. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102800. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102801. }
  102802. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102803. };
  102804. /**
  102805. * Setup the ground according to the specified options.
  102806. */
  102807. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102808. var _this = this;
  102809. if (!this._ground || this._ground.isDisposed()) {
  102810. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102811. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102812. this._ground.parent = this._rootMesh;
  102813. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102814. }
  102815. this._ground.receiveShadows = this._options.enableGroundShadow;
  102816. };
  102817. /**
  102818. * Setup the ground material according to the specified options.
  102819. */
  102820. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102821. if (!this._groundMaterial) {
  102822. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102823. }
  102824. this._groundMaterial.alpha = this._options.groundOpacity;
  102825. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102826. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102827. this._groundMaterial.primaryColor = this._options.groundColor;
  102828. this._groundMaterial.useRGBColor = false;
  102829. this._groundMaterial.enableNoise = true;
  102830. if (this._ground) {
  102831. this._ground.material = this._groundMaterial;
  102832. }
  102833. };
  102834. /**
  102835. * Setup the ground diffuse texture according to the specified options.
  102836. */
  102837. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102838. if (!this._groundMaterial) {
  102839. return;
  102840. }
  102841. if (this._groundTexture) {
  102842. return;
  102843. }
  102844. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102845. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102846. return;
  102847. }
  102848. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102849. diffuseTexture.gammaSpace = false;
  102850. diffuseTexture.hasAlpha = true;
  102851. this._groundMaterial.diffuseTexture = diffuseTexture;
  102852. };
  102853. /**
  102854. * Setup the ground mirror texture according to the specified options.
  102855. */
  102856. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102857. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102858. if (!this._groundMirror) {
  102859. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102860. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102861. this._groundMirror.anisotropicFilteringLevel = 1;
  102862. this._groundMirror.wrapU = wrapping;
  102863. this._groundMirror.wrapV = wrapping;
  102864. this._groundMirror.gammaSpace = false;
  102865. if (this._groundMirror.renderList) {
  102866. for (var i = 0; i < this._scene.meshes.length; i++) {
  102867. var mesh = this._scene.meshes[i];
  102868. if (mesh !== this._ground &&
  102869. mesh !== this._skybox &&
  102870. mesh !== this._rootMesh) {
  102871. this._groundMirror.renderList.push(mesh);
  102872. }
  102873. }
  102874. }
  102875. }
  102876. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102877. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102878. };
  102879. /**
  102880. * Setup the ground to receive the mirror texture.
  102881. */
  102882. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102883. if (this._groundMaterial) {
  102884. this._groundMaterial.reflectionTexture = this._groundMirror;
  102885. this._groundMaterial.reflectionFresnel = true;
  102886. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102887. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102888. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102889. }
  102890. };
  102891. /**
  102892. * Setup the skybox according to the specified options.
  102893. */
  102894. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102895. var _this = this;
  102896. if (!this._skybox || this._skybox.isDisposed()) {
  102897. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102898. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102899. }
  102900. this._skybox.parent = this._rootMesh;
  102901. };
  102902. /**
  102903. * Setup the skybox material according to the specified options.
  102904. */
  102905. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102906. if (!this._skybox) {
  102907. return;
  102908. }
  102909. if (!this._skyboxMaterial) {
  102910. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102911. }
  102912. this._skyboxMaterial.useRGBColor = false;
  102913. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102914. this._skyboxMaterial.enableNoise = true;
  102915. this._skybox.material = this._skyboxMaterial;
  102916. };
  102917. /**
  102918. * Setup the skybox reflection texture according to the specified options.
  102919. */
  102920. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102921. if (!this._skyboxMaterial) {
  102922. return;
  102923. }
  102924. if (this._skyboxTexture) {
  102925. return;
  102926. }
  102927. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102928. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102929. return;
  102930. }
  102931. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102932. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102933. this._skyboxTexture.gammaSpace = false;
  102934. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102935. };
  102936. /**
  102937. * Dispose all the elements created by the Helper.
  102938. */
  102939. EnvironmentHelper.prototype.dispose = function () {
  102940. if (this._groundMaterial) {
  102941. this._groundMaterial.dispose(true, true);
  102942. }
  102943. if (this._skyboxMaterial) {
  102944. this._skyboxMaterial.dispose(true, true);
  102945. }
  102946. this._rootMesh.dispose(false);
  102947. };
  102948. /**
  102949. * Default ground texture URL.
  102950. */
  102951. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102952. /**
  102953. * Default skybox texture URL.
  102954. */
  102955. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102956. /**
  102957. * Default environment texture URL.
  102958. */
  102959. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102960. return EnvironmentHelper;
  102961. }());
  102962. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102963. })(BABYLON || (BABYLON = {}));
  102964. //# sourceMappingURL=babylon.environmentHelper.js.map
  102965. var BABYLON;
  102966. (function (BABYLON) {
  102967. /** Internal class used to store shapes for emitters */
  102968. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102969. function ParticleSystemSetEmitterCreationOptions() {
  102970. }
  102971. return ParticleSystemSetEmitterCreationOptions;
  102972. }());
  102973. /**
  102974. * Represents a set of particle systems working together to create a specific effect
  102975. */
  102976. var ParticleSystemSet = /** @class */ (function () {
  102977. function ParticleSystemSet() {
  102978. /**
  102979. * Gets the particle system list
  102980. */
  102981. this.systems = new Array();
  102982. }
  102983. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102984. /**
  102985. * Gets the emitter node used with this set
  102986. */
  102987. get: function () {
  102988. return this._emitterNode;
  102989. },
  102990. enumerable: true,
  102991. configurable: true
  102992. });
  102993. /**
  102994. * Creates a new emitter mesh as a sphere
  102995. * @param options defines the options used to create the sphere
  102996. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102997. * @param scene defines the hosting scene
  102998. */
  102999. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  103000. if (this._emitterNode) {
  103001. this._emitterNode.dispose();
  103002. }
  103003. this._emitterCreationOptions = {
  103004. kind: "Sphere",
  103005. options: options,
  103006. renderingGroupId: renderingGroupId
  103007. };
  103008. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  103009. emitterMesh.renderingGroupId = renderingGroupId;
  103010. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  103011. material.emissiveColor = options.color;
  103012. emitterMesh.material = material;
  103013. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103014. var system = _a[_i];
  103015. system.emitter = emitterMesh;
  103016. }
  103017. this._emitterNode = emitterMesh;
  103018. };
  103019. /**
  103020. * Starts all particle systems of the set
  103021. * @param emitter defines an optional mesh to use as emitter for the particle systems
  103022. */
  103023. ParticleSystemSet.prototype.start = function (emitter) {
  103024. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103025. var system = _a[_i];
  103026. if (emitter) {
  103027. system.emitter = emitter;
  103028. }
  103029. system.start();
  103030. }
  103031. };
  103032. /**
  103033. * Release all associated resources
  103034. */
  103035. ParticleSystemSet.prototype.dispose = function () {
  103036. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103037. var system = _a[_i];
  103038. system.dispose();
  103039. }
  103040. this.systems = [];
  103041. if (this._emitterNode) {
  103042. this._emitterNode.dispose();
  103043. this._emitterNode = null;
  103044. }
  103045. };
  103046. /**
  103047. * Serialize the set into a JSON compatible object
  103048. * @returns a JSON compatible representation of the set
  103049. */
  103050. ParticleSystemSet.prototype.serialize = function () {
  103051. var result = {};
  103052. result.systems = [];
  103053. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  103054. var system = _a[_i];
  103055. result.systems.push(system.serialize());
  103056. }
  103057. if (this._emitterNode) {
  103058. result.emitter = this._emitterCreationOptions;
  103059. }
  103060. return result;
  103061. };
  103062. /**
  103063. * Parse a new ParticleSystemSet from a serialized source
  103064. * @param data defines a JSON compatible representation of the set
  103065. * @param scene defines the hosting scene
  103066. * @param gpu defines if we want GPU particles or CPU particles
  103067. * @returns a new ParticleSystemSet
  103068. */
  103069. ParticleSystemSet.Parse = function (data, scene, gpu) {
  103070. if (gpu === void 0) { gpu = false; }
  103071. var result = new ParticleSystemSet();
  103072. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  103073. scene = scene || BABYLON.Engine.LastCreatedScene;
  103074. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  103075. var system = _a[_i];
  103076. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  103077. }
  103078. if (data.emitter) {
  103079. var options = data.emitter.options;
  103080. switch (data.emitter.kind) {
  103081. case "Sphere":
  103082. result.setEmitterAsSphere({
  103083. diameter: options.diameter,
  103084. segments: options.segments,
  103085. color: BABYLON.Color3.FromArray(options.color)
  103086. }, data.emitter.renderingGroupId, scene);
  103087. break;
  103088. }
  103089. }
  103090. return result;
  103091. };
  103092. return ParticleSystemSet;
  103093. }());
  103094. BABYLON.ParticleSystemSet = ParticleSystemSet;
  103095. })(BABYLON || (BABYLON = {}));
  103096. //# sourceMappingURL=babylon.particleSystemSet.js.map
  103097. var BABYLON;
  103098. (function (BABYLON) {
  103099. /**
  103100. * This class is made for on one-liner static method to help creating particle system set.
  103101. */
  103102. var ParticleHelper = /** @class */ (function () {
  103103. function ParticleHelper() {
  103104. }
  103105. /**
  103106. * This is the main static method (one-liner) of this helper to create different particle systems
  103107. * @param type This string represents the type to the particle system to create
  103108. * @param scene The scene where the particle system should live
  103109. * @param gpu If the system will use gpu
  103110. * @returns the ParticleSystemSet created
  103111. */
  103112. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  103113. if (gpu === void 0) { gpu = false; }
  103114. if (!scene) {
  103115. scene = BABYLON.Engine.LastCreatedScene;
  103116. ;
  103117. }
  103118. var token = {};
  103119. scene._addPendingData(token);
  103120. return new Promise(function (resolve, reject) {
  103121. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  103122. scene._removePendingData(token);
  103123. return reject("Particle system with GPU is not supported.");
  103124. }
  103125. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  103126. scene._removePendingData(token);
  103127. var newData = JSON.parse(data.toString());
  103128. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  103129. }, undefined, undefined, undefined, function (req, exception) {
  103130. scene._removePendingData(token);
  103131. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  103132. });
  103133. });
  103134. };
  103135. /**
  103136. * Static function used to export a particle system to a ParticleSystemSet variable.
  103137. * Please note that the emitter shape is not exported
  103138. * @param system defines the particle systems to export
  103139. */
  103140. ParticleHelper.ExportSet = function (systems) {
  103141. var set = new BABYLON.ParticleSystemSet();
  103142. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  103143. var system = systems_1[_i];
  103144. set.systems.push(system);
  103145. }
  103146. return set;
  103147. };
  103148. /**
  103149. * Gets or sets base Assets URL
  103150. */
  103151. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  103152. return ParticleHelper;
  103153. }());
  103154. BABYLON.ParticleHelper = ParticleHelper;
  103155. })(BABYLON || (BABYLON = {}));
  103156. //# sourceMappingURL=babylon.particleHelper.js.map
  103157. var BABYLON;
  103158. (function (BABYLON) {
  103159. /**
  103160. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  103161. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  103162. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  103163. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103164. */
  103165. var VideoDome = /** @class */ (function (_super) {
  103166. __extends(VideoDome, _super);
  103167. /**
  103168. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  103169. * @param name Element's name, child elements will append suffixes for their own names.
  103170. * @param urlsOrVideo defines the url(s) or the video element to use
  103171. * @param options An object containing optional or exposed sub element properties
  103172. */
  103173. function VideoDome(name, urlsOrVideo, options, scene) {
  103174. var _this = _super.call(this, name, scene) || this;
  103175. _this._useDirectMapping = false;
  103176. // set defaults and manage values
  103177. name = name || "videoDome";
  103178. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103179. options.clickToPlay = Boolean(options.clickToPlay);
  103180. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  103181. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  103182. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103183. if (options.useDirectMapping === undefined) {
  103184. _this._useDirectMapping = true;
  103185. }
  103186. else {
  103187. _this._useDirectMapping = options.useDirectMapping;
  103188. }
  103189. // create
  103190. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  103191. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103192. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  103193. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103194. // configure material
  103195. material.useEquirectangularFOV = true;
  103196. material.fovMultiplier = 1.0;
  103197. material.opacityFresnel = false;
  103198. if (_this._useDirectMapping) {
  103199. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103200. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103201. material.diffuseTexture = texture;
  103202. }
  103203. else {
  103204. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103205. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103206. material.reflectionTexture = texture;
  103207. }
  103208. // configure mesh
  103209. _this._mesh.material = material;
  103210. _this._mesh.parent = _this;
  103211. // optional configuration
  103212. if (options.clickToPlay) {
  103213. scene.onPointerUp = function () {
  103214. _this._videoTexture.video.play();
  103215. };
  103216. }
  103217. return _this;
  103218. }
  103219. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  103220. /**
  103221. * Gets the video texture being displayed on the sphere
  103222. */
  103223. get: function () {
  103224. return this._videoTexture;
  103225. },
  103226. enumerable: true,
  103227. configurable: true
  103228. });
  103229. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  103230. /**
  103231. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103232. * Also see the options.resolution property.
  103233. */
  103234. get: function () {
  103235. return this._material.fovMultiplier;
  103236. },
  103237. set: function (value) {
  103238. this._material.fovMultiplier = value;
  103239. },
  103240. enumerable: true,
  103241. configurable: true
  103242. });
  103243. /**
  103244. * Releases resources associated with this node.
  103245. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103246. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103247. */
  103248. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103249. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103250. this._videoTexture.dispose();
  103251. this._mesh.dispose();
  103252. this._material.dispose();
  103253. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103254. };
  103255. return VideoDome;
  103256. }(BABYLON.Node));
  103257. BABYLON.VideoDome = VideoDome;
  103258. })(BABYLON || (BABYLON = {}));
  103259. //# sourceMappingURL=babylon.videoDome.js.map
  103260. var BABYLON;
  103261. (function (BABYLON) {
  103262. /**
  103263. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  103264. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  103265. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  103266. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  103267. */
  103268. var PhotoDome = /** @class */ (function (_super) {
  103269. __extends(PhotoDome, _super);
  103270. /**
  103271. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  103272. * @param name Element's name, child elements will append suffixes for their own names.
  103273. * @param urlsOfPhoto define the url of the photo to display
  103274. * @param options An object containing optional or exposed sub element properties
  103275. */
  103276. function PhotoDome(name, urlOfPhoto, options, scene) {
  103277. var _this = _super.call(this, name, scene) || this;
  103278. _this._useDirectMapping = false;
  103279. // set defaults and manage values
  103280. name = name || "photoDome";
  103281. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  103282. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  103283. if (options.useDirectMapping === undefined) {
  103284. _this._useDirectMapping = true;
  103285. }
  103286. else {
  103287. _this._useDirectMapping = options.useDirectMapping;
  103288. }
  103289. // create
  103290. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  103291. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  103292. // configure material
  103293. material.opacityFresnel = false;
  103294. material.useEquirectangularFOV = true;
  103295. material.fovMultiplier = 1.0;
  103296. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  103297. // configure mesh
  103298. _this._mesh.material = material;
  103299. _this._mesh.parent = _this;
  103300. return _this;
  103301. }
  103302. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  103303. /**
  103304. * Gets or sets the texture being displayed on the sphere
  103305. */
  103306. get: function () {
  103307. return this._photoTexture;
  103308. },
  103309. set: function (value) {
  103310. if (this._photoTexture === value) {
  103311. return;
  103312. }
  103313. this._photoTexture = value;
  103314. if (this._useDirectMapping) {
  103315. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103316. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103317. this._material.diffuseTexture = this._photoTexture;
  103318. }
  103319. else {
  103320. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  103321. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  103322. this._material.reflectionTexture = this._photoTexture;
  103323. }
  103324. },
  103325. enumerable: true,
  103326. configurable: true
  103327. });
  103328. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  103329. /**
  103330. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  103331. * Also see the options.resolution property.
  103332. */
  103333. get: function () {
  103334. return this._material.fovMultiplier;
  103335. },
  103336. set: function (value) {
  103337. this._material.fovMultiplier = value;
  103338. },
  103339. enumerable: true,
  103340. configurable: true
  103341. });
  103342. /**
  103343. * Releases resources associated with this node.
  103344. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  103345. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  103346. */
  103347. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  103348. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  103349. this._photoTexture.dispose();
  103350. this._mesh.dispose();
  103351. this._material.dispose();
  103352. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  103353. };
  103354. return PhotoDome;
  103355. }(BABYLON.Node));
  103356. BABYLON.PhotoDome = PhotoDome;
  103357. })(BABYLON || (BABYLON = {}));
  103358. //# sourceMappingURL=babylon.photoDome.js.map
  103359. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  103360. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};